I have a backend model with some properties that I want to be able to send to the frontend with certain properties excluded. I'd like to use typing to help me ensure they have been excluded.
I tried this approach of having an interface for the model and then a restricted interface using Omit<> to exclude the property.
interface Thing {
foo: string
secret: string
}
interface RestrictedThing extends Omit<Base, "secret"> {}
const thing: Thing = { foo: "test", secret: "must_exclude_in_restricted"}
const restricted: RestrictedThing = { ...thing } //does not complain
Unfortunately, when using the spread operator, typescript doesn't warn that there are properties present that should not be part of RestrictedThing.
I discovered ts-essentials StrictOmit but it only checks that the properties passed in are valid so it doesn't fit the bill.
I also tried using typeof without success
declare var { bar, ...forRestricted }: Thing;
type RestrictedThing = typeof forRestricted;
Is there a way to safely create a copy of my Thing object that uses typing to exclude unwanted properties?
Other approaches also welcome.
Base
? What isbar
? Could you edit to make sure this is a minimal reproducible example without typos or private/third-party code? It makes it hard to proceed if we have to debug the question to get to the starting point. • AssumingBase
is a typo forThing
, this has nothing to do with the spread operator; this code has the same lack of error. What, specifically would spread be doing here?const r: Restricted = { ...thing }
an error in TS, like this, but nothing will actually remove the property unless you do it yourself. TS types have no effect, whatsoever, on runtime behavior. So, are you looking for a type that prohibitssecret
? Or a line of runtime code that removessecret
from an object? Please edit to clarify.