设置作为参数传递的 TypeScript 对象的默认值 [英] Setting default value for TypeScript object passed as argument

查看:23
本文介绍了设置作为参数传递的 TypeScript 对象的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆