你可以为 TypeScript 泛型指定多个类型约束吗 [英] Can You Specify Multiple Type Constraints For TypeScript Generics
本文介绍了你可以为 TypeScript 泛型指定多个类型约束吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这个例子一样的通用接口,只有一个类型约束:
I have a generic interface like this example with a single type constraint:
export interface IExample<T extends MyClass> {
getById(id: number): T;
}
是否可以指定多个类型约束而不是一个?
Is it possible to specify multiple type constraints instead of just one?
推荐答案
Typescript 没有提供语法来获取泛型类型的多重继承.但是,您可以通过使用联合类型和交集类型来实现类似的语义.在你的情况下,你想要一个交叉点:
Typescript doesn't offer a syntax to get multiple inheritance for generic types. However, you can achieve similar semantics by using the Union types and Intersection types. In your case, you want an intersection :
interface Example<T extends MyClass & OtherClass> {}
对于两种类型的联合:
interface Example<T extends MyClass | OtherClass> {}
这篇关于你可以为 TypeScript 泛型指定多个类型约束吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文