为作为参数传递的 TypeScript 对象设置默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23314806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:15:13  来源:igfitidea点击:

Setting default value for TypeScript object passed as argument

typescript

提问by AJP

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');

And in coffeescript you have access to the conditional existence operator so can do:

在 coffeescript 中,您可以访问条件存在运算符,因此可以执行以下操作:

param.lastName ?= 'smith'

Which compiles to the javascript:

编译成 javascript:

if (param.lastName == null) {
    param.lastName = 'smith';
}

回答by jpadvo

Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:

实际上,现在似乎有一个简单的方法。以下代码适用于 TypeScript 1.5:

function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
  const name = first + ' ' + last;
  console.log(name);
}

sayName({ first: 'Bob' });

The trick is to first put in brackets what keys you want to pick from the argument object, with key=valuefor any defaults. Follow that with the :and a type declaration.

诀窍是首先将您想从参数对象中选择的键放在括号中,key=value用于任何默认值。使用:和 类型声明。

This is a little different than what you were trying to do, because instead of having an intact paramsobject, you have instead have dereferenced variables.

这与您尝试做的有点不同,因为params您没有完整的对象,而是拥有取消引用的变量。

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();

回答by encrest

Typescript supports default parameters now:

Typescript 现在支持默认参数:

https://www.typescriptlang.org/docs/handbook/functions.html

https://www.typescriptlang.org/docs/handbook/functions.html

Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:

此外,添加默认值允许您省略类型声明,因为它可以从默认值推断出来:

function sayName(firstName: string, lastName = "Smith") {
  const name = firstName + ' ' + lastName;
  alert(name);
}

sayName('Bob');

回答by Benson

Object destructuringthe parameter object is what many of the answers above are aiming for and Typescript now has the methods in place to make it much easier to read and intuitively understand.

对象解构参数对象是上述许多答案的目标,并且 Typescript 现在拥有适当的方法,使其更易于阅读和直观理解。

Destructuring Basics:By destructuring an object, you can choose properties from an object by key name. You can define as few or as many of the properties you like, and default values are set by a basic syntax of let {key = default} = object.

解构基础:通过解构对象,您可以通过键名从对象中选择属性。您可以定义任意数量或任意数量的属性,默认值由let {key = default} = object.

let {firstName, lastName = 'Smith'} = myParamsObject;

//Compiles to:
var firstName = myParamsObject.firstName, 
_a = myParamsObject.lastName, 
lastName = _a === void 0 ? 'Smith' : _a;

Writing an interface, type or class for the parameter object improves legibility.

为参数对象编写接口、类型或类可提高易读性。

type FullName = {
  firstName: string;
   
  /** @default 'Smith' */
  lastName ? : string;
}

function sayName(params: FullName) {

  // Set defaults for parameter object
  var { firstName, lastName = 'Smith'} = params;

  // Do Stuff
  var name = firstName + " " + lastName;
  alert(name);
}

// Use it
sayName({
  firstName: 'Bob'
});

回答by WiredPrairie

No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:

不,TypeScript 没有一种自然的方法来为定义的对象属性设置默认值,就像一个有默认值而另一个没有。您可以定义更丰富的结构:

class Name {
    constructor(public first : string, 
        public last: string = "Smith") {

    }
}

And use that in place of the inline type definition.

并使用它代替内联类型定义。

function sayName(name: Name) {
    alert(name.first + " " + name.last);
}

You can't do something like this unfortunately:

不幸的是,你不能做这样的事情:

function sayName(name : { first: string; last?:string } 
       /* and then assign a default object matching the signature */  
       = { first: null, last: 'Smith' }) {

} 

As it would only set the default if namewas undefined.

因为它只会设置默认值 if nameis undefined

回答by Cameron

This can be a nice way to do it that does not involve long constructors

这可能是一个很好的方法,不涉及长构造函数

class Person {
    firstName?: string = 'Bob';
    lastName?: string = 'Smith';

    // Pass in this class as the required params
    constructor(params: Person) {
        // object.assign will overwrite defaults if params exist
        Object.assign(this, params)
    }
}

// you can still use the typing 
function sayName(params: Person){ 
    let name = params.firstName + params.lastName
    alert(name)
}

// you do have to call new but for my use case this felt better
sayName(new Person({firstName: 'Gordon'}))
sayName(new Person({lastName: 'Thomas'}))

回答by Ben Dev

Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.

这里有一些可以尝试的东西,使用接口并使用默认值进行解构。请注意,“姓氏”是可选的。

interface IName {
  firstName: string
  lastName?: string
}

function sayName(params: IName) {
  const { firstName, lastName = "Smith" } = params
  const fullName = `${firstName} ${lastName}`

  console.log("FullName-> ", fullName)
}

sayName({ firstName: "Bob" })

回答by Aakil Fernandes

Without destructuring, you can create a defaults params and pass it in

无需解构,您可以创建一个默认参数并将其传入

interface Name {
   firstName: string;
   lastName: string;
}

export const defaultName extends Omit<Name, 'firstName'> {
    lastName: 'Smith'
}

sayName({ ...defaultName, firstName: 'Bob' })