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;
}
答案 0 :(得分:0)
打字稿中没有这样的约束。最好的办法是使用枚举的基本类型,在这种情况下为number
(如果需要使用字符串枚举,则可以使用string
或string | 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>