MST

星途 面试题库

面试题:TypeScript中默认参数与可选参数优先级规则的基础应用

在TypeScript中,定义一个函数,该函数同时包含默认参数和可选参数。请解释在调用这个函数时,参数的匹配规则是怎样的,并举例说明。
25.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 定义函数示例
function greet(name: string = 'Guest', message?: string) {
    if (message) {
        return `Hello, ${name}! ${message}`;
    } else {
        return `Hello, ${name}!`;
    }
}
  1. 参数匹配规则
    • 默认参数:如果调用函数时没有传递对应参数,那么函数会使用默认参数的值。在上述例子中,如果调用 greet()name 参数会使用默认值 'Guest'
    • 可选参数:可选参数在调用函数时可以省略。当省略可选参数时,函数内部会判断该参数是否存在(如上述例子中对 message 参数的判断)。如果传递了可选参数,函数就会使用传递的值。
  2. 调用示例
    • 只使用默认参数:
let result1 = greet();
console.log(result1); 
// 输出: Hello, Guest!
- 使用传递的参数和默认参数:
let result2 = greet('Alice');
console.log(result2); 
// 输出: Hello, Alice!
- 使用传递的参数和可选参数:
let result3 = greet('Bob', 'Have a nice day!');
console.log(result3); 
// 输出: Hello, Bob! Have a nice day!