你可以为 TypeScript 泛型指定多个类型约束吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17125764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:05:34  来源:igfitidea点击:

Can You Specify Multiple Type Constraints For TypeScript Generics

typescripttypescript-generics

提问by Fenton

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?

是否可以指定多个类型约束而不是一个?

回答by STO

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 :

Typescript 不提供语法来获取泛型类型的多重继承。但是,您可以通过使用联合类型和交集类型来实现类似的语义。在你的情况下,你想要一个交集:

interface Example<T extends MyClass & OtherClass> {}

For a Union of both types :

对于两种类型的联合:

interface Example<T extends MyClass | OtherClass> {}

回答by Fenton

A work around for this would be to use a super-interface (which also answers the question "why would you allow an interface to inherit from a class").

解决这个问题的方法是使用超级接口(它也回答了“为什么允许接口从类继承”的问题)。

interface ISuperInterface extends MyClass, OtherClass {

}

export interface IExample<T extends ISuperInterface> {
    getById(id: number): T;
}

回答by andyks

Ref the comment about an interface deriving from a class...whats in a name?

参考关于从类派生的接口的评论......名称中有什么?

I found this in section 3.5 of the 0.9.0 spec:

我在 0.9.0 规范的第 3.5 节中发现了这一点:

Interface declarations only introduce named types, whereas class declarations introduce named types and constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can't declare optional members and interfaces can't declare private members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations.

接口声明仅引入命名类型,而类声明引入命名类型和创建这些命名类型实现实例的构造函数。类和接口声明引入的命名类型只有很小的区别(类不能声明可选成员,接口不能声明私有成员)并且在大多数上下文中是可以互换的。特别是,只有公共成员的类声明引入了命名类型,其功能与接口声明创建的类型完全相同。