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

我曾想象过这样的东西可能有用:

function sayName(params: {firstName: string; lastName: string = 'smith'}) {

显然,如果这些是简单的参数,你可以这样做:

function sayName(firstName: string, lastName = 'smith') {
    var name = firstName + lastName;
    alert(name);
}

sayName('bob');

在coffeescript中,你可以访问条件存在操作符,所以可以这样做:

param.lastName ?= 'smith'

编译成javascript:

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

当前回答

实际上,现在似乎有一种简单的方法。以下代码适用于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。后面跟着:和一个类型声明。

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

如果您希望将任何内容传递给函数为可选,请添加?对于类型中的所有键,在类型声明后添加默认值={}:

function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
    var name = first + " " + last;
    alert(name);
}

sayName();

其他回答

这是一种不涉及长构造函数的好方法

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

Typescript现在支持默认参数:

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

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

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

sayName('Bob');

还有另一种不需要解构的方法,就是用这样的类型设置默认值:

function name(param1:type=defaultValue1, paramr2:type=defaultvalue2,...) {//}

一个例子是

function addTwoNumbers(first:number = 1, second:number = 3):number {return first+second}
console.log(addTwoNumbers())

不需要解构,您可以创建一个默认的params并将其传入

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

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

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

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

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" })