我需要使用 TypeScript 多載一個方法。
FooModel有 6 個引數,但只有 2 個字串引數是必需的引數。因此,不是每次我想使用myMethod 時都創建一個FooModel,我想多載myMethod并在那里創建一次FooModel,然后在回傳之前創建其余的邏輯。
我已經根據到目前為止在網上找到的內容進行了嘗試,但出現以下錯誤:
TS2394: This overload signature is not compatible with its implementation signature.
此錯誤的解決方案與我的方法不兼容
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
}
uj5u.com熱心網友回復:
問題
來自 TypeScript 的檔案:
多載簽名和實作簽名
這是混淆的常見來源。通常人們會寫這樣的代碼,但不明白為什么會出現錯誤:
function fn(x: string): void;
function fn() {
// ...
}
// Expected to be able to call with zero arguments
fn();
^^^^
Expected 1 arguments, but got 0.
同樣,用于撰寫函式體的簽名不能從外部“看到”。
從外部看不到實作的簽名。撰寫多載函式時,應始終在函式實作上方有兩個或多個簽名。
實作簽名還必須與多載簽名兼容。例如,這些函式有錯誤,因為實作簽名沒有以正確的方式匹配多載:
function fn(x: boolean): void;
// Argument type isn't right
function fn(x: string): void;
^^
This overload signature is not compatible with its implementation signature.
function fn(x: boolean) {}
function fn(x: string): string;
// Return type isn't right
function fn(x: number): boolean;
^^
This overload signature is not compatible with its implementation signature.
function fn(x: string | number) {
return "oops";
}
–關于多載和實作簽名的 TypeScript 檔案
在您的情況下,您已經定義了以下多載簽名:
static async myMethod(model: FooModel): Promise<BarResult>
但是實作簽名沒有重疊。實作簽名中的第一個引數是stringwhile 多載是FooModel而實作簽名中的第二個引數是stringwhile 多載是undefined。
static async myMethod(inputText: string, outputText: string): Promise<BarResult>{
解決方案
將您當前的實作簽名轉換為多載并添加與您的兩個多載兼容的實作簽名:
class Foo {
static async myMethod(model: FooModel): Promise<BarResult>;
static async myMethod(inputText: string, outputText: string): Promise<BarResult>;
static async myMethod(modelOrInputText: string | FooModel, outputText?: string): Promise<BarResult>{
//implementation;
return new BarResult(); //Different content based on the inputs
}
}
–打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332679.html
下一篇:創建Mysql程序或函式時出錯
