MST
星途 面试题库

面试题:TypeScript中默认参数与可选参数兼容性基础考察

请解释在TypeScript中,默认参数和可选参数在函数定义与使用上的主要区别,并举例说明它们如何影响函数调用时的参数传递。另外,当一个函数同时包含默认参数和可选参数时,在类型兼容性方面需要注意什么?
32.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 默认参数和可选参数在函数定义上的区别
    • 默认参数:在函数定义时,为参数指定一个默认值。语法上,直接在参数名后使用 = 赋值。例如:
function greet(name = 'world') {
    console.log(`Hello, ${name}!`);
}
  • 可选参数:在函数定义时,在参数名后加上 ? 表示该参数是可选的。例如:
function greetOptional(name?: string) {
    if (name) {
        console.log(`Hello, ${name}!`);
    } else {
        console.log('Hello!');
    }
}
  1. 默认参数和可选参数在函数使用上的区别
    • 默认参数:调用函数时,如果没有传递该参数,函数会使用默认值。传递参数时,会使用传递的值覆盖默认值。例如:
greet(); // 输出: Hello, world!
greet('John'); // 输出: Hello, John!
  • 可选参数:调用函数时,可以传递该参数,也可以不传递。当不传递时,函数内部需要处理该参数可能为 undefined 的情况。例如:
greetOptional(); // 输出: Hello!
greetOptional('Jane'); // 输出: Hello, Jane!
  1. 当函数同时包含默认参数和可选参数时在类型兼容性方面的注意事项
    • 当一个函数同时包含默认参数和可选参数时,在类型兼容性检查时,默认参数的类型必须与可选参数的类型兼容。例如:
function combine(a: number, b?: number, c = 10) {
    return a + (b || 0) + c;
}
// 定义一个类型兼容的函数
function anotherCombine(a: number, b: number, c: number) {
    return a + b + c;
}
let func: (a: number, b: number, c: number) => number;
func = combine; // 这是允许的,因为默认参数和可选参数类型兼容
  • 如果默认参数类型与可选参数类型不兼容,会导致类型错误。例如:
// 以下代码会报错,因为c的默认值类型string与b的可选类型number不兼容
function incorrectCombine(a: number, b?: number, c = 'ten') {
    return a + (b || 0) + c; // 这里会有类型错误
}

总结来说,默认参数和可选参数在函数定义和使用上有明显区别,同时存在时要注意类型兼容性以避免错误。