如何模拟“ T扩展枚举”泛型约束?

时间:2019-03-26 12:01:30

标签: typescript enums

I'm already aware that TypeScript does not allow enums as constraints,但是有没有办法-即使是骇人听闻的人-也能获得类似的行为?

export enum StandardSortOrder {
    Default,
    Most,
    Least
}

export enum AlternativeOrder {
    Default,
    High,
    Medium,
    Low
}

export interface IThingThatUsesASortOrder<T extends enum> { // doesn't compile
    sortOrder: T;
}

1 个答案:

答案 0 :(得分:0)

打字稿中没有这样的约束。最好的办法是使用枚举的基本类型,在这种情况下为number(如果需要使用字符串枚举,则可以使用stringstring | number都允许)

export enum StandardSortOrder {
    Default,
    Most,
    Least
}

export enum AlternativeOrder {
    Default,
    High,
    Medium,
    Low
}

export interface IThingThatUsesASortOrder<T extends number> { 
    sortOrder: T;
}

let a: IThingThatUsesASortOrder<StandardSortOrder>
let a2: IThingThatUsesASortOrder<AlternativeOrder>