在 TypeScript 中,函数默认参数 (Default Parameter) 是一种常用的语法特性。本文将深入探讨 TypeScript 中默认参数的用法和技巧,以及如何更好的利用默认参数提高代码的可读性和复用性。
什么是默认参数
默认参数是指在定义函数时,给函数形参赋予一个初始值,当调用函数时,如果没有给形参传入值,则形参将会使用默认值。
例如,下面代码定义了一个加法函数:
function add(num1: number, num2: number = 0): number {
return num1 + num2;
}
console.log(add(3, 5)); // 输出 8
console.log(add(3)); // 输出 3(num2 默认值为 0)在这个例子中,我们定义了一个加法函数 add,有两个形参 num1 和 num2。其中,num2 的默认值为 0,如果调用函数时不传入 num2 的值,则 num2 将会使用默认值 0。
TypeScript 中的默认参数
在 TypeScript 中,默认参数可以被指定类型,并且可以在参数列表的任意位置设置,默认参数的值可以是常量、表达式、函数调用等。
例如,下面代码定义了一个 greet 函数,参数列表中 greetWords 和 name 都是默认参数:
function greet(greetWords = 'Hello', name: string = 'World'): void {
console.log(`${greetWords}, ${name}!`);
}
greet('Hi', 'TypeScript'); // 输出 Hi, TypeScript!
greet(undefined, 'TypeScript'); // 输出 Hello, TypeScript!(greetWords 使用默认值)
greet(undefined, undefined); // 输出 Hello, World!(greetWords 和 name 都使用默认值)默认参数的注意事项
在使用默认参数时,需要注意以下几个问题:
参数默认值的类型
当定义默认参数时,需要指定默认值的类型,否则其类型将被 TypeScript 推断为 any 类型。
例如,下面代码中的 name 参数将推断出类型为 any 类型:
function greet(greetWords = 'Hello', name = 'World') {
console.log(`${greetWords}, ${name}!`);
}
greet(); // 输出 Hello, World!如果你想要避免这种情况,可以手动为参数赋予类型,例如:
function greet(greetWords: string = 'Hello', name: string = 'World') {
console.log(`${greetWords}, ${name}!`);
}
greet(); // 输出 Hello, World!默认参数不会传递到 undefined 实参
使用默认参数时,如果某个参数被明确地传入 undefined 值,那么该默认参数将不会使用默认值,而是使用 undefined,例如:
function greet(greetWords = 'Hello', name: string = 'World'): void {
console.log(`${greetWords}, ${name}!`);
}
greet(undefined, 'TypeScript'); // 输出 Hello, TypeScript!(greetWords 使用默认值)默认参数与可选参数的区别
在 TypeScript 中,默认参数与可选参数有区别。
默认参数是指在定义函数时,为参数设置一个默认值,当调用函数时,如果没有传递该参数的值,则使用默认值。
而可选参数是指在定义函数时,为参数指定一个问号 ?,该参数可以不传递值。当调用函数时,如果该参数没有传递值,则该参数的值为 undefined。
例如,下面代码中的 name 参数是可选参数,而 greetWords 是默认参数:
function greet(greetWords = 'Hello', name?: string): void {
console.log(`${greetWords}, ${name || 'World'}!`);
}
greet('Hi', 'TypeScript'); // 输出 Hi, TypeScript!
greet(undefined, 'TypeScript'); // 输出 Hello, TypeScript!(greetWords 使用默认值)
greet(); // 输出 Hello, World!(greetWords 和 name 都使用默认值)从上面的例子可以看出,如果某个参数可能会传入 undefined,那么可以使用可选参数。否则,使用默认参数。
结语
本文详细讲解了 TypeScript 中的默认参数,包括默认参数的定义、注意事项等。在实际编码过程中,掌握默认参数的用法可以帮助我们更好地编写可读性高、复用性强的代码,编写出更加健壮的应用程序。
示例代码可以在 我的 GitHub 仓库 中查看。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67d6996da941bf7134c62a36