![](/img/trans.png)
[英]TypeScript - How do you infer a class generic type from a method's parameter?
[英]How to infer the generic return type that is bound to a generic parameter of a parameterized class in a typescript method?
我有以下超類,T應該是API返回的類型
export class Command<T> {
}
這是一個擴展命令的登錄命令:
export class LoginCommand extends Command<LoginResult> {
username: string;
password: string;
}
和返回對象:
export class LoginResult {
success: boolean;
token: string;
}
調用方法時:
public call<R>(command: model.command.Command<R>): R {
return null as R; // code omitted
}
具有以下參數:
const cmd = new LoginCommand();
const success = this.call(cmd).success;
它會產生錯誤: [ts]類型“ {}”上不存在屬性“成功”
問題1 :如何修改方法簽名以正確地從Command推斷R為返回類型? 我還嘗試了以下語法,結果相同:
public call<T extends Command<R>, R>(command: T): R
問題2 :為什么ask方法接受不擴展Command的參數? 傳遞字符串不會產生任何錯誤。
最后一個問題最容易回答,您的Command
基類沒有屬性或方法,因此任何類型在結構上都等同於它,包括字符串。
問題的另一部分更加困難,如果您從泛型類型傳遞派生類型,則編譯器將不會向下鑽取以推斷出泛型參數。
您可以執行以下操作之一:
將with
操作添加到Command
類
export class Command<T> {
private something: "";
with(fn: (cmd: Command<T>) => T) : T{
return fn(this);
}
}
//Usage:
public call<R>(command: Command<R>): R {
return null as R; // code omitted
}
public doStuff() {
const cmd = new LoginCommand();
const success = cmd.with(this.call).success; // Works
}
向基類添加簡單的轉換方法
export class Command<T> {
private something: "";
asCmd(): Command<T> { return this;}
}
public doStuff() {
const cmd = new LoginCommand();
const success = this.call(cmd.asCmd()).success;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.