Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate "T extends enum" generic constraint?

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;
}
like image 456
Ian Kemp Avatar asked Jan 29 '26 10:01

Ian Kemp


1 Answers

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>
like image 163
Titian Cernicova-Dragomir Avatar answered Jan 31 '26 03:01

Titian Cernicova-Dragomir