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

Viewed 3465

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

2 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

I think you are looking for Exclude utility type:

 sources: Exclude<MyEnum, MyEnum.ALL>
Related