【问题标题】:Optional deconstruction function parameter可选解构函数参数
【发布时间】:2017-12-06 22:28:49
【问题描述】:

如何修改下面的函数使第二个参数可选?

TypeScript:

function getName(name: string, {
    lastName
  }: {
    lastName: string
  }) {
  // ...
}

getName('John'); // error

更新:

目前我找到的解决方案是将解构取出到函数体中:

function getName(name: string, options: {
    lastName: string
  } = {} as any) {
    const { lastName } = options;
    // ...
}

getName('John'); // OK

但是,我仍然找不到如何使它在这种情况下工作:

const getName = Bluebird.coroutine(function* co(name: string,
  {
    lastName
  }: {
    lastName: string
  }) {
    // ...
});

getName('John'); // error


/* -------- DECLARATIONS -------- */

declare namespace Bluebird {
    interface CoroutineOptions {
        yieldHandler(value: any): any;
    }
}

declare class Bluebird<R> {
    static coroutine<T, A1, A2>(
        generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
        options?: Bluebird.CoroutineOptions
    ): (a1: A1, a2: A2) => Bluebird<T>;
}

把解构移到函数体还是报错:

const getName = Bluebird.coroutine(function* co(name: string, options: {
    lastName: string
  } = {} as any) {
    // ...
});

getName('John'); // error: Expected 2 arguments but got 1.

【问题讨论】:

  • 查看更新,语法正确吗?我不知道示例中使用了function*coroutine。这能清楚地显示吗?

标签: javascript typescript ecmascript-6


【解决方案1】:

在定义选项对象时,您需要将lastName 属性的接口定义为可选。如果未定义 options,则默认对象为空对象 {}。

function foo(required: string, options: { lastName?: string } = {}) {
    console.log(required);
    if (options.lastName) {
        console.log(options.lastName);
    }
}

foo('foo1')
foo('foo2', {})
foo('foo3', {lastName: 'bar'})

运行上述,控制台输出为:

foo1
foo2
foo3
bar

请参阅TypeScript playground link 亲自尝试一下。

【讨论】:

  • 我在问题中更新时取出解构作品。在使用 Bluebird 协程时,还有一个我想不通的情况。请查看更新后的问题。
【解决方案2】:

options = {} 应该可以吗?

function getName(name: string, options = {}) {}

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 2019-02-26
    • 1970-01-01
    • 2023-04-04
    • 2016-11-26
    • 2019-10-02
    • 2021-03-12
    • 2023-01-31
    • 2012-10-15
    相关资源
    最近更新 更多