相关疑难解决方法(0)

即使参数满足每个函数的约束,也不能调用函数的并集

我正在尝试编译此Typescript代码段:

function foo(v: string) { return 'foo'; }
function bar(v: string | number) { return 'bar'; }

const notCallable: typeof foo | typeof bar = function() {} as any;

// Fails type check, even though all the unioned functions accept string.
notCallable('a');
Run Code Online (Sandbox Code Playgroud)

编译器推断notCallableas 的类型((v: string) => string) | ((v: string | number) => string),看起来不错,但不被视为可调用:

无法调用类型缺少调用签名的表达式。输入'(((v:string)=> string)| (((v:字符串|数字)=>字符串)'没有兼容的呼叫签名。

请注意,如果参数列表匹配,则即使返回类型不同,它也可以正常工作。

function foo(v: string) { return 'foo'; }
function bar(v: string) { return 0; }

const callable: typeof foo …
Run Code Online (Sandbox Code Playgroud)

typescript

7
推荐指数
1
解决办法
1454
查看次数

标签 统计

typescript ×1