使用枚举中的键时排除枚举项

时间:2019-01-12 14:12:20

标签: typescript

我有一个这样的枚举(稍大一点):

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

我用它来定义需要这种键的类型:

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

所以在我的课堂上,我可以做类似的事情:

private memberWithFunctions: MyTypeKeyFunctionValue; 

现在,当某些成员需要将所有键都放在MyTypeEnum中(让我说two)而我不知道如何定义排除该键的类型时,我的情况特别特殊但保留所有其他键。

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以只使用Exclude条件类型从enum中删除成员

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

答案 1 :(得分:0)

使用Omit类型跳过属性。

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

用法:

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