项目的monorepo前段时间在应用eslint规则集时遇到了这个规则
@typescript-eslint/method-signature-style[1]
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,List-A和list-D的分配关系是什么呢?
协变保留分配兼容性,逆变则与之相反
协变(covariant),如果它保持了子类型序关系≦[2]。该序关系是:子类型≦基类型。即List-D可以分配给List-A
逆变(contravariant),如果它逆转了子类型序关系。List-A可以分配给 List-D
双向协变 (Bivariant) List-A与List-D可以互相分配
不变 (Invariant) List-A和 List-D不存在分配关系,或者说无法互相分配
存在的意义?
子类型可以隐性的转换为父类型
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的结果区别是什么
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[3]有这么一句话
Methods are excluded specifically to ensure generic classes and interfaces (such as
Array<T>
) continue to mostly relate covariantly.
如果翻看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为双向协变
为了保证类型安全我们应当
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);
[1]@typescript-eslint/method-signature-style: https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/method-signature-style.md
[2]子类型序关系≦: https://link.zhihu.com/?target=https://zh.wikipedia.org/wiki/%E5%AD%90%E5%9E%8B%E5%88%A5
[3]PR: https://github.com/microsoft/TypeScript/pull/18654
以上便是本次分享的全部内容,希望对你有所帮助^_^
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8