我试图从传入的泛型参数推断出方法的返回类型。但是,该参数是来自于一个泛型接口的实现,因此我认为typescript推断应该可以从该参数的基类中确定类型。
示例代码:
interface ICommand<T> {}
class GetSomethingByIdCommand implements ICommand<string> {
constructor(public readonly id: string) {}
}
class CommandBus implements ICommandBus {
execute<T>(command: ICommand<T>): T {
return null as any // ignore this, this will be called through an interface eitherway
}
}
const bus = new CommandBus()
// badResult is {}
let badResult = bus.execute(new GetSomethingByIdCommand('1'))
// goodResult is string
let goodResult = bus.execute<string>(new GetSomethingByIdCommand('1'))
我希望做的是第一个
execute
调用,并让 TypeScript 推断出正确的返回值,在这种情况下,根据实现自 GetSomethingByIdCommand
推导得到的是 string
。我尝试过使用 条件类型 进行操作,但不确定是否可行或如何应用。
ICommand<T>
接口没有对T
的使用进行限制。因此,你的GetSomethingByIdCommand
类 隐式实现 了ICommand<number>
(例如)。实际上,该类似乎是ICommand<T>
的实现 *适用于任何类型T
*。鉴于此,TypeScript 如何选择推断哪种类型呢? - CRiceGetSomethingByIdCommand
显式实现ICommand<string>
时,它是如何隐式实现ICommand<number>
的?能否详细解释一下? - Jake Holzinger