【发布时间】:2018-02-05 00:44:49
【问题描述】:
我有以下超类,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] 类型“{}”上不存在属性“成功”
问题一:如何修改方法签名以正确推断 R from Command 作为返回类型?我还尝试了以下语法,结果相同:
public call<T extends Command<R>, R>(command: T): R
问题2:为什么 ask 方法接受不扩展 Command 的参数?传入字符串不会产生错误。
【问题讨论】:
标签: typescript generics