MST

星途 面试题库

面试题:TypeScript类型兼容性在函数参数中的复杂应用

已知有两个函数类型`Func1`和`Func2`,`Func1`的定义为`(a: {x: number, y: number}) => void`,`Func2`的定义为`(a: {x: number}) => void`。请判断`Func1`和`Func2`哪个类型可以赋值给另一个,详细说明判断依据,并通过代码验证你的结论。
12.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 判断依据
    • 在TypeScript中,函数类型的赋值遵循逆变(contravariance)原则。对于函数参数,目标类型的参数必须能够接受源类型参数所能接受的一切值。
    • Func1的参数类型是{x: number, y: number}Func2的参数类型是{x: number}
    • 一个类型为{x: number}的值可以被当作类型为{x: number, y: number}的值来使用(因为它满足{x: number}这个子集要求),所以Func2类型的函数可以赋值给Func1类型的变量。
    • 但是,一个类型为{x: number, y: number}的值不能保证能被当作类型为{x: number}的值来使用(因为可能存在额外的y属性),所以Func1类型的函数不能赋值给Func2类型的变量。
  2. 代码验证
// 定义Func1和Func2类型
type Func1 = (a: {x: number, y: number}) => void;
type Func2 = (a: {x: number}) => void;

// 尝试将Func2赋值给Func1,这是可行的
const func1: Func1 = (obj) => {
    console.log(obj.x, obj.y);
};
const func2: Func2 = (obj) => {
    console.log(obj.x);
};
func1 = func2;

// 尝试将Func1赋值给Func2,这会报错
// const func3: Func2 = func1;
// 报错信息:Type 'Func1' is not assignable to type 'Func2'.
//   Types of parameters 'a' and 'a' are incompatible.
//     Type '{ x: number; }' is not assignable to type '{ x: number; y: number; }'.
//       Property 'y' is missing in type '{ x: number; }' but required in type '{ x: number; y: number; }'.

所以,Func2类型可以赋值给Func1类型,而Func1类型不能赋值给Func2类型。