MST

星途 面试题库

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

假设我们有两个函数类型`type Func1 = (x: number) => void`和`type Func2 = (x: number | string) => void`。请问`Func1`和`Func2`谁兼容谁?如果将一个类型为`Func1`的函数赋值给一个类型为`Func2`的变量,或者反之,会出现什么情况?请解释原因并举例说明。
33.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 兼容性分析
    • Func1兼容Func2。原因在于Func1函数接受number类型参数,而Func2函数接受numberstring类型参数。从类型赋值兼容性角度看,当把一个函数赋值给另一个类型的变量时,赋值函数(源类型)的参数类型要能满足目标类型函数的参数类型要求。对于Func1,其参数类型是numbernumber类型是number | string联合类型的一部分,所以Func1类型的函数可以赋值给Func2类型的变量。
    • 反之,Func2不兼容Func1。因为Func2函数可能接受string类型参数,而Func1函数只能接受number类型参数,string类型不是Func1参数类型number的子类型,所以不能将Func2类型的函数赋值给Func1类型的变量。
  2. 举例说明
    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;