前言
为什么需要引入逆变、协变和双向协变这些概念
因为考虑到类型兼容
,详情参考https://www.typescriptlang.org/docs/handbook/type-compatibility.html
在 TypeScript 中,有两种兼容性机制:子类型和赋值
(意思是理解成在子类型和赋值这种操作下才会触发兼容性,比如比较该类型是不是其子类型)
出于实际目的,类型兼容性由赋值兼容性决定
,即使在implements and extends子句的情况下也是如此
基础
TypeScript中的类型兼容性可以用于确定一个类型是否可以赋值给其他类型。这里要了解两个概念:
官方文档说到TS 是结构性的类型系统(Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing. Consider the following code)
结构类型:一种只使用其成员来描述类型的方式(类型 ducking type);
名义类型:明确的指出或声明其类型,如c#,java。
TypeScript的类型兼容性就是基于结构子类型的。下面的例子: