I have a enum and interface like this
enum MyEnum {
ALL, OTHER
}
interface Props {
sources: Omit<MyEnum, MyEnum.ALL>
}
const test: Props = { sources: MyEnum.ALL } // should complain
Why does it not omit MyEnum.All
? I am using typescript 3.6.4
Use the Exclude utility type to omit values from an enum, e.g. type WithoutMultiple = Exclude<Sizes, Sizes. Small | Sizes. Medium> . The Exclude utility type constructs a new type by excluding the provided members from the original type.
The they are useless at runtime argument This is a false argument for typescript in general, let alone Enums. and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.
Alternatives to enums: string unions and object literals.
Omit
is to omit keys from an interface. But enums are something different.
Imo the best comparison of an enum would be a union of instances of that enum type. Like type MyEnum = MyEnum.All | MyEnum.OTHER
.
So you do not want to OMIT keys, but exclude types from an union type:
enum MyEnum {
ALL, OTHER, SOME, MORE
}
interface Props {
sources: Exclude<MyEnum, MyEnum.ALL | MyEnum.SOME>
}
const test: Props = { sources: MyEnum.ALL } // does complain now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With