如何将泛型参数的类型限制为Typescript函数作为枚举 [英] How to constrain the type of generic parameter to a Typescript function to be an enum

查看:337
本文介绍了如何将泛型参数的类型限制为Typescript函数作为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将输入参数的类型约束为通用Typescript函数,使其成为Typescript枚举?

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

换句话说,我想强制执行该T下面的函数中的是一个非常量Typescript枚举
Foo< T>(){/ * * /}

In other words, I want to enforce that T in the function below is a non-constant 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.

这篇关于如何将泛型参数的类型限制为Typescript函数作为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆