TypeScript类型中的逆变协变

418次阅读  |  发布于2年以前

缘起

项目的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的分配关系是什么呢?

协变保留分配兼容性,逆变则与之相反

存在的意义?

子类型可以隐性的转换为父类型

类型的位置影响逆变协变

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[3]有这么一句话

Methods are excluded specifically to ensure generic classes and interfaces (such asArray<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为双向协变

总结

为了保证类型安全我们应当

作业


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