MST
星途 面试题库

面试题:TypeScript函数重载中的类型推断与多态

假设有一个函数`printValue`,它需要根据传入参数类型不同进行不同的打印操作。参数可能是`string`、`number`或`boolean`类型。请使用函数重载实现该功能,并解释在这个过程中TypeScript是如何进行类型推断以实现多态的。
49.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

函数重载实现

function printValue(value: string): void;
function printValue(value: number): void;
function printValue(value: boolean): void;
function printValue(value: string | number | boolean): void {
    if (typeof value ==='string') {
        console.log(`字符串: ${value}`);
    } else if (typeof value === 'number') {
        console.log(`数字: ${value}`);
    } else if (typeof value === 'boolean') {
        console.log(`布尔值: ${value}`);
    }
}

TypeScript类型推断与多态实现解释

  1. 函数重载声明:通过多次声明同名函数,但参数类型不同,告诉TypeScript该函数可以接受不同类型的参数。例如,printValue(value: string): void; 声明该函数可以接受一个 string 类型参数且无返回值。这使得TypeScript在调用函数时能够根据传入参数的类型来确定使用哪个函数定义。
  2. 联合类型实现:实际实现函数时,使用联合类型 string | number | boolean 来涵盖所有可能的参数类型。在函数体内部,通过 typeof 操作符进行类型检查,根据不同类型执行不同的打印逻辑,从而实现多态行为。
  3. 类型推断:在调用 printValue 函数时,TypeScript会根据传入的实际参数类型,从多个重载声明中选择最合适的一个。比如调用 printValue('hello'),TypeScript能推断出应该使用 printValue(value: string): void 这个声明,从而确保类型安全和正确的函数行为。这种类型推断机制使得代码在编译时就能检测到类型错误,同时通过不同的函数实现逻辑实现了多态效果。