Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Omit<T,K> does not work for enums

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

like image 226
Murat Karagöz Avatar asked Oct 21 '19 11:10

Murat Karagöz


People also ask

How do you omit an enum?

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.

Are enums bad in TypeScript?

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.

What can I use instead of enums TypeScript?

Alternatives to enums: string unions and object literals.


1 Answers

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
like image 68
Thomas Avatar answered Sep 23 '22 06:09

Thomas