如何简洁调用带默认参数的TypeScript函数,跳过中间参数?
解决方案
首先注意你的函数定义存在语法错误:gender: string = 'male'后面缺少逗号,修正后的函数定义如下:
function makeAnimal( animal: string, color: string, age: number = 3, gender: string = 'male', name: string = 'Barky' ){ // some code }
要实现仅传入animal、color和name参数,无需手动提供age和gender,有两种常用方式:
方式一:重构为对象参数(推荐)
将函数参数改为一个配置对象,这种方式最灵活,参数顺序不再受限,且能清晰指定要传递的参数:
// 重构后的函数 function makeAnimal({ animal, color, age = 3, gender = 'male', name = 'Barky' }: { animal: string; color: string; age?: number; gender?: string; name?: string; }){ // some code } // 调用方式 console.log(makeAnimal({ animal: 'dog', color: 'black', name: 'Marky' }));
方式二:使用undefined占位(无需重构函数)
利用参数默认值的特性,给age和gender位置传入undefined,会自动使用它们的默认值,直接传递name:
console.log(makeAnimal( 'dog', 'black', undefined, undefined, 'Marky' ));
内容的提问来源于stack exchange,提问作者KiritoLyn
相关产品推荐
相关产品推荐

