为作为参数传递的 TypeScript 对象设置默认值 [英] Setting default value for TypeScript object passed as argument
问题描述
function sayName(params: {firstName: string; lastName?: string}) {
params.lastName = params.lastName || 'smith'; // <<-- any better alternative to this?
var name = params.firstName + params.lastName
alert(name);
}
sayName({firstName: 'bob'});
我曾想象这样的事情可能会奏效:
I had imagined something like this might work:
function sayName(params: {firstName: string; lastName: string = 'smith'}) {
显然,如果这些是简单的论点,您可以这样做:
Obviously if these were plain arguments you could do it with:
function sayName(firstName: string, lastName = 'smith') {
var name = firstName + lastName;
alert(name);
}
sayName('bob');
在coffeescript中,您可以访问条件存在运算符,因此可以这样做:
And in coffeescript you have access to the conditional existence operator so can do:
param.lastName ?= 'smith'
编译成 javascript:
Which compiles to the javascript:
if (param.lastName == null) {
param.lastName = 'smith';
}
推荐答案
实际上,现在似乎有一个简单的方法.以下代码适用于 TypeScript 1.5:
Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
诀窍是首先将您想从参数对象中选择的键放在括号中,key=value
用于任何默认值.使用 :
和类型声明.
The trick is to first put in brackets what keys you want to pick from the argument object, with key=value
for any defaults. Follow that with the :
and a type declaration.
这与您尝试做的有点不同,因为您没有完整的 params
对象,而是具有取消引用的变量.
This is a little different than what you were trying to do, because instead of having an intact params
object, you have instead have dereferenced variables.
如果您希望将任何内容传递给函数,请为类型中的所有键添加一个 ?
,并在后面添加一个默认值 ={}
类型声明:
If you want to make it optional to pass anything to the function, add a ?
for all keys in the type, and add a default of ={}
after the type declaration:
function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
var name = first + " " + last;
alert(name);
}
sayName();
这篇关于为作为参数传递的 TypeScript 对象设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!