【发布时间】:2021-02-27 11:52:09
【问题描述】:
我有一个使用可选参数调用的重载函数。我无法弄清楚如何让 Typescript 正确地找到其中的错误。
function inner<T>(innerArg: T) {
function foo(): T;
function foo(a: boolean): T & { a: boolean };
// function foo(a?: boolean): T | T & { a: boolean };
function foo(a?: boolean) {
return a ? { ...innerArg, a } : innerArg;
}
return foo;
}
function wrapper<T>(outerArg: T, a?: boolean) {
return inner(outerArg)(a); // Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolean'.
}
const arg = { b: 1 }
console.log(wrapper(arg).b); // 1
console.log(wrapper(arg, true).a); // true
console.log(wrapper(arg, true).b); // 1
console.log(wrapper(arg).a); // should generate compilation error
如果我取消注释第四行,添加一个带有可选的重载签名,包装器中的错误就会消失。但是,从第三行到最后一行出现错误,
console.log(wrapper(arg, true).a);
哪个应该是有效的,哪个打印'true'。
有没有一种输入 inner 的方法,以便 Typescript 能够正确识别 inner 和 wrapper 的正确和不正确用法?
【问题讨论】:
标签: typescript