Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constrain the type of generic parameter to a Typescript function to be an enum

Is it possible to constrain the type of an input parameter to a generic Typescript function to be a Typescript enum?

In other words, I want to enforce that T in the function below is a non-constant Typescript enum Foo<T>() { /* */ }

like image 805
ebhh2001 Avatar asked Jun 25 '16 21:06

ebhh2001


1 Answers

You can constrain the type to a specific enum.

function foo<T extends MyEnum>(param: T) {    
}

However, you cannot constrain it to be any enum (see specs).

In addition to generic interfaces, we can also create generic classes. Note that it is not possible to create generic enums and namespaces.

like image 122
Tomas Nikodym Avatar answered Oct 19 '22 18:10

Tomas Nikodym