如何限制通用接口在打字稿中接受特定数据类型?
我知道,在typescript中的通用接口中定义哪些数据类型可以接受。
interface exampleInterface<T = void | any>;
但是,如果我想限制接口接受一种或两种特定的数据类型怎么办?
注意:
我已经查看了以下问题,应该提到它与我的问题相反,因为它谈论了如何定义哪些数据类型是可以接受的,而我试图在此通用界面中定义哪些数据类型是不可接受的。
将通用类型限制在类型
How do I restrict a generic interface from accepting a specific data type in typescript?
I know that to define what data types are acceptable to be passed in a generic interface in typescript.
interface exampleInterface<T = void | any>;
but what if I want restrict my interface from accepting one or two specific data types?
Note:
I have already viewed the following question and should mention that it is opposite of my question as it talks about how to define what data types ARE acceptable while I am trying to define what data types ARE NOT acceptable to be passed in this generic interface.
Restricting generic types to one of several classes in Typescript
发布评论
评论(1)
这样做的一种方法是定义
type
这样的方法:在这种情况下,不允许使用
字符串
和undefined
。然后,您可以这样使用它:
唯一的缺点是
类型
,而不是问题中指定的接口
。但是,您始终可以使用界面和例如添加道具之类的类型:Playground
One way to do this would be to define a
type
like this:In this case
string
andundefined
wouldn't be allowed.You could then use it like this:
The only downside to this is this being a
type
and not aninterface
as you specified in your question. But you can always use types like an interface and e.g. add props:Playground