TypeScript类型中的逆变协变
协变 (Covariant) 、逆变 (Contravariant) 、双向协变 (Bivariant) 和不变 (Invariant)
www.typescriptlang.org/play
缘起
项目的monorepo前段时间在应用eslint规则集时遇到了这个规则
@typescript-eslint/method-signature-style
规则案例
???? 不推荐写法
interface T1 { func(arg: string): number; } type T2 = { func(arg: boolean): void; }; interface T3 { func(arg: number): void; func(arg: string): void; func(arg: boolean): void; } 复制代码
????推荐写法
interface T1 { func: (arg: string) => number; } type T2 = { func: (arg: boolean) => void; }; // this is equivalent to the overload interface T3 { func: ((arg: number) => void) & ((arg: string) => void) & ((arg: boolean) => void); } 复制代码
原因
该规则声称开启是一个能享受函数类型检查的不错的实践(需要配合 typescript的strictFunctionTypes
模式)
A method and a function property of the same type behave differently. Methods are always bivariant in their argument, while function properties are contravariant in their argument under
strictFunctionTypes
.
可能有同学看到这句话和我当时一样懵逼,何谓contravariant,methods和function properties为何区别对待?
逆变协变
可分配性
declare const a: string const b: string = a 复制代码
a是安全地赋值给b的,因为 string 可分配给string。
在ts中决定类型之间的可分配性是基于结构化类型(structural typing)的,什么是结构化类型?这个结构化的类型有什么表现呢?可能大家都听过一个叫做"鸭子类型"的谚语:
If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
class Animal { public weight: number = 0; } class Dog extends Animal { public wang() { console.log("wang") } } class Cat extends Animal { public miao() { console.log("miao") } } declare const cat:Cat const animal:Animal =cat // work 复制代码
在ts的类型系统中,如果T可分配给U,ts只关心这个类型的表现是什么,不关心这个类型叫什么名称,只要T的表现跟U一样,ts认为T可分配给U是安全的。
逆变协变是什么?
假设Dog是Animal的子类型(subtype),Dog可以分配给Animal,此时有个List<T>,List<Animal>和list<Dog>的分配关系是什么呢?
协变保留分配兼容性,逆变则与之相反
协变(covariant),如果它保持了子类型序关系≦。该序关系是:子类型≦基类型。即List可以分配给List
逆变(contravariant),如果它逆转了子类型序关系。 List<Animal> 可以分配给 List<Dog>
双向协变 (Bivariant) List<Animal> 与List<Dog>可以互相分配
不变 (Invariant) List<Animal> 和 List<Dog>不存在分配关系,或者说无法互相分配
存在的意义?
子类型可以隐性的转换为父类型
类型的位置影响逆变协变
返回值 -> 协变
F1: () => Cat F2: () => Animal 复制代码
入参
通常应该为逆变
const f1: (cat: Cat) => void = (cat) => { cat.miao(); } const f2: (animal: Animal) => void = (animal) => { console.log(animal.weight) } // error, 因为不是所有的animal都能miao const f3: (animal: Animal) => void = f1; f3(new Animal()); // success,因为所有的cat都有weight const f4: (cat: Cat) => void = f2; f4(new Cat()) 复制代码
函数属性与函数方法
类型校验
interface Animal { name: string; } interface Dog extends Animal { wang: () => void; } interface Cat extends Animal { miao: () => void; } interface Comparer<T> { compare(a: T, b: T): number; } declare let animalComparer: Comparer<Animal>; declare let dogComparer: Comparer<Dog>; animalComparer = dogComparer; // Ok because of bivariance dogComparer = animalComparer; // Ok 复制代码
interface Animal { name: string; } interface Dog extends Animal { wang: () => void; } interface Cat extends Animal { miao: () => void; } interface Comparer<T> { compare: (a: T, b: T) => number; } declare let animalComparer: Comparer<Animal>; declare let dogComparer: Comparer<Dog>; animalComparer = dogComparer; // Error dogComparer = animalComparer; // Ok 复制代码
typescript认为函数方法的入参是双向协变,函数属性的入参是逆变(开启strictFunctionTypes
以后),为什么呢?
JS
我们来看看这两种编译成js的结果区别是什么
class Greeter { constructor() { this.greet(); this.greet2(); this.greet3(); } greet() { console.log('greet1', this); } greet2 = () => { console.log('greet2', this); } greet3 = function() { console.log('greet3', this); } } let bla = new Greeter(); const b: Array<Greeter> = []; 复制代码
Compile.... =>
var Greeter = /** @class */ (function () { function Greeter() { var _this = this; this.greet2 = function () { console.log('greet2', _this); }; this.greet3 = function () { console.log('greet3', this); }; this.greet(); this.greet2(); this.greet3(); } Greeter.prototype.greet = function () { console.log('greet1', this); }; return Greeter; }()); var bla = new Greeter(); 复制代码
可以看到greet被写入了原型对象上,原生对象的通用方法也写在了原型,实际上typescript的这种行为是为了兼容js的行为,兼顾开发体验。
ts支持strictFunctionTypes
的PR有这么一句话
Methods are excluded specifically to ensure generic classes and interfaces (such as
Array<T>
) continue to mostly relate covariantly.
Array
可变数据
如果翻看typescript的Array的类型,可以看到Array的写的是方法
interface Array<T> { pop(): T | undefined; push(...items: T[]): number; concat(...items: ConcatArray<T>[]): T[]; // ... } 复制代码
当然,这种写法会造成类型的不安全
{ const dogs: Array<Dog> = []; const animals: Animal[] = dogs; // Array在ts中是双向协变 animals.push(new Cat()) // Is it safe? dogs.forEach((dog) => dog.wang()); } 复制代码
可变数组+ 双向协变 无法保证类型 安全
更安全的数组类型
我们可以做以下尝试
interface MutableArray<T> { pop: () => T | undefined; push: (...items: T[]) => number; concat:(...items: ConcatArray<T>[]) => T[]; join: (separator?: string) => string; reverse: () => T[]; shift:() => T | undefined; slice:(start?: number, end?: number) => T[]; sort:(compareFn?: (a: T, b: T) => number) => this; indexOf: (searchElement: T, fromIndex?: number) => number; } 复制代码
此时我们会发现MutableArray其实是个不可变类型,不再能互相分配
{ const dogs: MutableArray<Dog> = [] as Dog[]; // error const animals: MutableArray<Animal> = dogs; } { const animals: MutableArray<Animal> = [] as Animal[] ; // error const dogs: MutableArray<Dog> = animals } 复制代码
原因是Array类型既存在逆变方法push也存在协变方法pop,甚至还有不可变方法concat
解决方案
将协变和逆变分开
// 协变数组类型 interface CoArray<T> { pop: () => T | undefined; join: (separator?: string) => string; reverse: () => T[]; shift:() => T | undefined; slice:(start?: number, end?: number) => T[]; sort:(compareFn?: (a: T, b: T) => number) => this; } // 逆变数组类型 interface ContraArray<T> { push: (...items: T[]) => number; indexOf: (searchElement: T, fromIndex?: number) => number; } 复制代码
当然实际使用不可能有这种类型,最终TypeScript采用兼容方案,允许Array为双向协变
总结
为了保证类型安全我们应当
更多使用readonly保住类型不可变
更多使用函数属性而不是方法来定义类型
尝试让类型中的协变或者逆变分开,或者让类型不可变
尽量避免双向协变
作业
interface StatefulComponent { // 诸如 state: "stopped1"错误是可以默认检测出来的 setState(state: "started" | "stopped"): void; } function moveToPausedState(component: {setState(state: "started" | "stopped" | "paused"): void}) { component.setState("paused"); } const ListComponent: StatefulComponent = { setState(state): void { switch(state) { case "started": case "stopped": console.log(state); break; default: console.error(state); break } } } moveToPausedState(ListComponent);
作者:ELab
链接:https://juejin.cn/post/7039315081150087181