如何修改下面的功能以使第二个参数可选?
打字稿:
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.
答案 0 :(得分:4)
在定义options对象时,您需要将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自行试用。
答案 1 :(得分:2)
options = {}
应该有用吗?
function getName(name: string, options = {}) {}