Typescript 中的逆变与协变
概念:协变和逆变都是术语,前者指能够使用比原始指定的派生类型的派生程度更大(更具体的)的类型,后者指能够使用比原始指定的派生类型的派生程度更小(不太具体的)的类型 。 泛型类型参数支持协变和逆变,可在分配和使用泛型类型方面提供更大的灵活性。
一、typescript 协变
示例
type parent = string|number|boolean
type child = string|boolean
type test = child extends parent ? true:false
// test 的类型是true
let a:child = true;
let b:parent = 1;
a = b; // 报错 Type 'number' is not assignable to type 'child'.
b = a; // 不报错
结论: 如图中代码所示 child类型可以继承parent类型(child 为 parent的子类) 当我们创建两个变量 a = true、b = 1并且分别赋给它们child和parent类型的时候。如果这这时想把b赋值给a,就会报类型错误(Type ‘number’ is not assignable to type ‘child’.),说child里面没有