可选的解构函数参数 [英] Optional deconstruction function parameter

查看:103
本文介绍了可选的解构函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you modify the function below to make the second parameter optional?

TypeScript:

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

getName('John'); // error

更新:

到目前为止,我发现的解决方案是将解构方法放入函数主体中:

The solution I've found so far is to take out the deconstruction into the function body:

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

getName('John'); // OK

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

However, I still cannot find how to make it work in this context:

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

将解构函数移至函数主体仍会产生错误:

Moving the deconstruction to the function body still gives an error:

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

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

推荐答案

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

You will need to define the interface for the lastName property as optional when defining the options object. If no options is defined, the default object is an empty object {}.

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

运行以上命令,控制台输出为:

Running the above, the console output is:

foo1
foo2
foo3
bar

请参见 查看全文

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