简体   繁体   English

什么是TypeScript中的F界多态

[英]What is F-Bounded Polymorphism in TypeScript

I notice version 1.8 of TypeScript supports F-Bounded Polymorphism . 我注意到TypeScript版本1.8支持F绑定多态 In layman's terms, what is it and how is this helpful? 用外行的话来说,这是什么?它有什么帮助? I am assuming since this feature was included early it must be pretty important. 我假设由于早已包含此功能,因此它必须非常重要。

It basically means that you have your list of generics that the function references, and within that list of generics, one type can reference another type, to define a relationship between the two generic types. 基本上,这意味着您拥有函数引用的泛型列表,并且在该泛型列表中,一种类型可以引用另一种类型,以定义两种泛型类型之间的关系。

function someFunction <T, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Cat());

Hooray! 万岁!

Now, with bounded generics, they can reference one another to define the bounds of the relationship they have with each other: 现在,有了有界的泛型,他们可以互相引用来定义彼此之间的关系的界限:

function someFunction <T extends U, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Pet());
const cow = someFunction(new Cow(), new Animal());
const BOOM = someFunction(new Cat(), new Dog()); // *BEWM!*

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

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