函数类型兼容:协变与逆变
协变和逆变描述:当类型之间存在子类型关系时,包含它们的函数等类型如何保持或反转这一关系。以下函数参数示例以开启 strictFunctionTypes 为前提。
先建立可区分的类型
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const dog: Dog = { name: 'Buddy', bark: () => console.log('Woof') };
Dog 拥有 Animal 要求的全部成员,因此可以赋给 Animal;反过来,普通 Animal 不一定有 bark。使用两个没有成员的空类无法有效演示差异,因为 TypeScript 主要按结构判断兼容性。
返回值协变
type ReturnsAnimal = () => Animal;
type ReturnsDog = () => Dog;
const getAnimal: ReturnsAnimal = () => ({ name: 'Animal' });
const getDog: ReturnsDog = () => dog;
const animalGetter: ReturnsAnimal = getDog;
// @ts-expect-error 返回普通 Animal 的函数不能保证返回 Dog
const dogGetter: ReturnsDog = getAnimal;
需要 Animal 的调用方可以接收更具体的 Dog,因此 () => Dog 可以赋给 () => Animal。返回值的兼容方向与 Dog → Animal 一致,称为协变。
参数逆变
type TakesAnimal = (animal: Animal) => void;
type TakesDog = (dog: Dog) => void;
const handleAnimal: TakesAnimal = animal => console.log(animal.name);
const handleDog: TakesDog = dog => dog.bark();
const dogHandler: TakesDog = handleAnimal;
dogHandler(dog);
// @ts-expect-error 只会处理 Dog 的函数不能处理任意 Animal
const animalHandler: TakesAnimal = handleDog;
承诺只传入 Dog 的位置,可以使用能处理所有 Animal 的函数。反过来,需要接收任意 Animal 的位置不能使用仅支持 Dog 的函数,因为调用方可能传入没有 bark 的对象。
所以 (Animal) => void 可以赋给 (Dog) => void,函数类型的方向与参数的子类型方向相反,称为逆变。
同时检查参数和返回值
type AnimalProcessor = (animal: Animal) => Animal;
type DogProcessor = (dog: Dog) => Dog;
const processAnimal: AnimalProcessor = animal => animal;
const processDog: DogProcessor = dog => dog;
const createDog = (_animal: Animal): Dog => dog;
// 接收范围足够宽,返回结果足够具体:两种位置都能使用
const dogProcessor: DogProcessor = createDog;
const animalProcessor: AnimalProcessor = createDog;
// @ts-expect-error 返回值 Animal 不能满足 Dog
const invalidDogProcessor: DogProcessor = processAnimal;
// @ts-expect-error 参数 Dog 无法接收任意 Animal
const invalidAnimalProcessor: AnimalProcessor = processDog;
参数兼容与返回值兼容必须同时成立。不能只因为返回值协变,就认为整个函数可以赋值。
strictFunctionTypes 与方法双向协变
strictFunctionTypes 对函数类型参数采用更严格的逆变检查,strict 默认包含此选项。关闭它会放宽参数检查,允许一些可能产生运行时错误的赋值。
方法声明是一个兼容性例外,其参数采用双向协变检查:
interface FunctionHandler<T> {
handle: (value: T) => void; // 函数属性:严格检查
}
interface MethodHandler<T> {
handle(value: T): void; // 方法签名:双向协变
}
const dogFunctionHandler: FunctionHandler<Dog> = { handle: handleDog };
// @ts-expect-error 函数属性不能在这里缩窄参数类型
const animalFunctionHandler: FunctionHandler<Animal> = dogFunctionHandler;
const dogMethodHandler: MethodHandler<Dog> = { handle: handleDog };
const animalMethodHandler: MethodHandler<Animal> = dogMethodHandler; // 编译允许
// animalMethodHandler.handle({ name: 'Cat' }); // 运行时会因缺少 bark 而报错
“编译允许”不等于所有调用都安全。分析回调兼容性时,要结合编译选项以及函数属性、方法签名的区别。
不变类型与数组的实际行为
如果类型参数同时出现在严格检查的输入和输出位置,通常会形成不变关系:
interface Cell<T> {
get: () => T;
set: (value: T) => void;
}
const dogCell: Cell<Dog> = { get: () => dog, set: handleDog };
// @ts-expect-error set 不能接收任意 Animal
const animalCell: Cell<Animal> = dogCell;
只读数组主要提供输出,可以将 readonly Dog[] 赋给 readonly Animal[]。TypeScript 也允许将可变的 Dog[] 赋给 Animal[],但通过后者写入普通 Animal 可能破坏原数组的类型假设。因此,不能笼统地说 TypeScript 的可变数组默认是不变的。