MST

星途 面试题库

面试题:TypeScript函数类型注解中参数类型不匹配的常见问题及解决思路

在TypeScript中,定义一个函数`addNumbers`,期望接收两个数字参数并返回它们的和。如果调用该函数时传入了一个字符串参数,会出现什么类型错误?如何通过类型注解和代码修改来解决这个问题?请给出具体的代码示例。
22.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 错误描述:当传入字符串参数时,会出现类型不匹配错误,因为函数期望的参数类型是数字,而字符串不能直接用于数字加法运算。
  2. 解决方法:通过类型注解明确函数参数类型为数字,确保调用时传入正确类型。如果要兼容字符串类型,可以先进行类型检查并转换。

以下是代码示例:

// 正确定义函数,使用类型注解
function addNumbers(num1: number, num2: number): number {
    return num1 + num2;
}

// 调用函数
let result1 = addNumbers(1, 2); 
// console.log(result1);

// 处理可能传入字符串的情况
function addNumbersWithString(num1: string | number, num2: string | number): number {
    let num1Value: number;
    let num2Value: number;
    if (typeof num1 ==='string') {
        num1Value = parseFloat(num1);
    } else {
        num1Value = num1;
    }
    if (typeof num2 ==='string') {
        num2Value = parseFloat(num2);
    } else {
        num2Value = num2;
    }
    return num1Value + num2Value;
}

let result2 = addNumbersWithString('1', 2); 
// console.log(result2);