distante
distante

Reputation: 7005

Exclude enum item when using key in Enum

I have a enum like this (just a little bit bigger):

export enum MyTypeEnum {
    one = 'one',
    two = 'two',
    three = 'three',
    four = 'four'
}

I use it to define types that need to have those keys in this way:

export type MyTypeKeyFunctionValue = { [key in MyTypeEnum ]?: Function };
export type MyTypeKeyStringValue = { [key in MyTypeEnum ]?: string };

So in my class I can do something like:

private memberWithFunctions: MyTypeKeyFunctionValue; 

Now, I have a special situation when some member needs to have all the keys in MyTypeEnum BUT one (lets say two) and I do not know how to define a type that excludes that key but keeps all the other keys.

Is there a way to do this?

Upvotes: 5

Views: 6810

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249716

You can just use the Exclude conditional type to remove a member from the enum

export type MyTypeKeyStringValue = { 
    [key in Exclude<MyTypeEnum, MyTypeEnum.two> ]?: string
 };

Upvotes: 7

Karol Majewski
Karol Majewski

Reputation: 25800

Use the Omit type to skip a property.

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

Usage:

const foo: Omit<MyTypeKeyFunctionValue, MyTypeEnum.two> = {
  /* ... */
}

Upvotes: 0

Related Questions