Reputation: 29868
I'm already aware that TypeScript does not allow enums as constraints, but is there a way - even a hacky one - to get similar behaviour?
export enum StandardSortOrder {
Default,
Most,
Least
}
export enum AlternativeOrder {
Default,
High,
Medium,
Low
}
export interface IThingThatUsesASortOrder<T extends enum> { // doesn't compile
sortOrder: T;
}
Upvotes: 15
Views: 11108
Reputation: 249706
There is no such constraint in typescript. The best you can do is use the base type of the enum, which in this case is number
(if you need to use string enums then you would use string
or string | number
if you want to allow both)
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>
Upvotes: 9