Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How to create a type that enforces exclusion of properties in typescript when using spread operator?

$
0
0

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.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>