参数默认值
程序员文章站
2024-02-20 19:36:52
...
区别
在ES6中,可以给参数添加默认值
但是在TypeScript中,会将添加了默认值的参数识别为可选参数
补充一点,可选参数,与接口中的可选属性类似,用?表示可选的参数
function buildName(firstName: string, lastName?: string) {
if (lastName) {
return firstName + ' ' + lastName;
} else {
return firstName;
}
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');
注意:可选参数必须接在必需参数后面。换句话说,可选参数后面不允许再出现必需参数了
function buildName(firstName?: string, lastName: string) {
if (firstName) {
return firstName + ' ' + lastName;
} else {
return lastName;
}
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName(undefined, 'Tom');
// index.ts(1,40): error TS1016: 必选参数不能位于可选参数后。
参数默认值
function buildName(firstName: string, lastName: string = 'Cat') {
return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');
注意:此时就不受「可选参数必须接在必需参数后面」的限制了
function buildName(firstName: string = 'Tom', lastName: string) {
return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let cat = buildName(undefined, 'Cat');
上一篇: hbase-model-versions