【发布时间】:2021-05-26 16:54:11
【问题描述】:
我使用了一个第 3 方库,它定义了一个接口 (A) 和一个重载方法 (method)。该方法可以接受空值或字符串值作为参数。
我定义了一个联合类型:string | null,并将它作为参数传递给方法,但我得到一个错误:
No overload matches this call.
Overload 1 of 2, '(val: null): null', gave the following error.
Argument of type 'StringOrNull' is not assignable to parameter of type 'null'.
Type 'string' is not assignable to type 'null'.
Overload 2 of 2, '(val: string): string', gave the following error.
Argument of type 'StringOrNull' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.(2769)
这是我的代码: TypeScript Playgroud
interface A{
method(val: null): null;
method(val: string): string;
}
type StringOrNull = string | null;
function myFunc(obj: A, val: StringOrNull) {
obj.method(val); // Error: No overload matches this call.
}
为什么会发生这种情况,我该如何解决?
【问题讨论】:
-
我在你的例子中有三个错误。你能解决它吗?
-
@captain-yossarian 谢谢你的评论。我编辑了我的示例以仅包含相关错误。
标签: typescript overloading union-types