Allow "T extends enum" generic constraint
See original GitHub issueTypeScript has a discrete enum
type that allows various compile-time checks and constraints to be enforced when using such types. It would be extremely useful to allow generic constraints to be limited to enum types - currently the only way to do this is via T extends string | number
which neither conveys the intent of the programmer, nor imposes the requisite type enforcement.
export enum StandardSortOrder {
Default,
Most,
Least
}
export enum AlternativeSortOrder {
Default,
High,
Medium,
Low
}
export interface IThingThatUsesASortOrder<T extends enum> { // doesn't compile
sortOrder: T;
}
Issue Analytics
- State:
- Created 4 years ago
- Reactions:204
- Comments:27 (4 by maintainers)
Top Results From Across the Web
How to emulate "T extends enum" generic constraint?
There is no such constraint in typescript. The best you can do is use the base type of the enum, which in this...
Read more >Chapter 4. Using enums and generics - TypeScript Quickly
In this chapter, you'll learn how to use enums—a way to create a new type based on a limited set of values. We'll...
Read more >Dissecting new generic constraints in C# 7.3
The main change was related to generics, starting from C# 7.3 there 3 more constraints: unmanaged , System.Enum and System.Delegate .
Read more >Typescript Basics: Enums and Generics (Part 3) - Medium
Enums, short for enumerations, are a data type used in most object-oriented languages. Enums allow a way for developer to declare a group...
Read more >How to extend enums in TypeScript - LogRocket Blog
The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them. However, there are workarounds you ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I have a use case for this as well. I have a Select component that I want to make generic by taking any enum. I expect the caller to pass in a map of enumValue -> string labels.
If this feature existed, I could make a component like
Which would guarantee type-safety. (The compiler would prevent the developer ever forgetting to map a certain enum value to a user-friendly string representation)
Because I want to allow
IThingThatUsesASortOrder
to be used with any enum type.