【发布时间】: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