Mr.*_*r.B 4 methods overloading typescript
我需要使用 TypeScript 重载一个方法。
FooModel有 6 个参数,但 2 个字符串参数是唯一的强制参数。因此,我不想每次想使用myMethod时都创建FooModel,而是想重载myMethod并在其中创建一次FooModel,然后在返回之前创建其余逻辑。
我已经根据迄今为止在网上找到的内容尝试过此操作,但出现以下错误:
TS2394: This overload signature is not compatible with its implementation signature.
Run Code Online (Sandbox Code Playgroud)
该错误的解决方案与我的方法不兼容
static async myMethod(model: FooModel): Promise<BarResult>
static async myMethod(inputText: string, outputText: string): Promise<BarResult>{
//implementation;
return new BarResult(); //Different content based on the inputs
}
Run Code Online (Sandbox Code Playgroud)
来自 TypeScript 的文档:
\n\n\n重载签名和实现签名
\n这是造成混乱的常见原因。通常人们会编写这样的代码,但不明白为什么会出现错误:
\n
function fn(x: string): void;\nfunction fn() {\n // ...\n}\n// Expected to be able to call with zero arguments\nfn();\n^^^^\nExpected 1 arguments, but got 0.\n
Run Code Online (Sandbox Code Playgroud)\n\n\n同样,用于编写函数体的签名从外部不能是\xe2\x80\x99\xe2\x80\x9cseen\xe2\x80\x9d。
\n从外部看不到实现的签名。当编写重载函数时,您应该始终在函数的实现之上有两个或多个签名。
\n实现签名还必须与重载签名兼容。例如,这些函数有错误,因为实现签名\xe2\x80\x99与重载不以正确的方式匹配:
\n
function fn(x: boolean): void;\n// Argument type isn\'t right\nfunction fn(x: string): void;\n ^^\nThis overload signature is not compatible with its implementation signature.\n\nfunction fn(x: boolean) {}\n
Run Code Online (Sandbox Code Playgroud)\nfunction fn(x: string): string;\n// Return type isn\'t right\nfunction fn(x: number): boolean;\n ^^\nThis overload signature is not compatible with its implementation signature.\n\nfunction fn(x: string | number) {\n return "oops";\n}\n
Run Code Online (Sandbox Code Playgroud)\n\xe2\x80\x93有关重载和实现签名的 TypeScript 文档
\n在您的情况下,您定义了以下重载签名:
\nstatic async myMethod(model: FooModel): Promise<BarResult>\n
Run Code Online (Sandbox Code Playgroud)\n但实现签名没有重叠。实现签名中的第一个参数是string
while 重载是FooModel
,而实现签名中的第二个参数是string
while 重载是undefined
。
static async myMethod(inputText: string, outputText: string): Promise<BarResult>{\n
Run Code Online (Sandbox Code Playgroud)\n将当前的实现签名转换为重载,并添加与两个重载兼容的实现签名:
\nclass Foo {\n static async myMethod(model: FooModel): Promise<BarResult>;\n static async myMethod(inputText: string, outputText: string): Promise<BarResult>;\n static async myMethod(modelOrInputText: string | FooModel, outputText?: string): Promise<BarResult>{\n //implementation;\n return new BarResult(); //Different content based on the inputs\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\xe2\x80\x93 TypeScript 游乐场
\n 归档时间: |
|
查看次数: |
10865 次 |
最近记录: |