简体   繁体   English

如何将 Typescript 函数的泛型参数类型限制为枚举

[英]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?是否可以将输入参数的类型限制为通用 Typescript 函数为 Typescript 枚举?

In other words, I want to enforce that T in the function below is a non-constant Typescript enum Foo<T>() { /* */ }换句话说,我想强制下面函数中的 T 是一个非常量的 Typescript enum Foo<T>() { /* */ }

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.请注意,无法创建通用枚举和命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM