面试题答案
一键面试- 判断依据:
- 在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
类型的变量。
- 代码验证:
// 定义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
类型。