面试题答案
一键面试- 兼容性分析:
Func1
兼容Func2
。原因在于Func1
函数接受number
类型参数,而Func2
函数接受number
或string
类型参数。从类型赋值兼容性角度看,当把一个函数赋值给另一个类型的变量时,赋值函数(源类型)的参数类型要能满足目标类型函数的参数类型要求。对于Func1
,其参数类型是number
,number
类型是number | string
联合类型的一部分,所以Func1
类型的函数可以赋值给Func2
类型的变量。- 反之,
Func2
不兼容Func1
。因为Func2
函数可能接受string
类型参数,而Func1
函数只能接受number
类型参数,string
类型不是Func1
参数类型number
的子类型,所以不能将Func2
类型的函数赋值给Func1
类型的变量。
- 举例说明:
type Func1 = (x: number) => void; type Func2 = (x: number | string) => void; // 将Func1类型的函数赋值给Func2类型的变量,这是可行的 const func1: Func1 = (num) => { console.log(num); }; const func2: Func2 = func1; // 尝试将Func2类型的函数赋值给Func1类型的变量,这会报错 const func3: Func2 = (param) => { console.log(param); }; // 以下代码会报错:Type '(param: number | string) => void' is not assignable to type 'Func1'. // Types of parameters 'param' and 'x' are incompatible. // Type 'number' is not assignable to type 'number | string'. const func4: Func1 = func3;