I'm trying to infer the return type of a method from the generic of an argument passed in. However, the argument is an implementation from a generic interface, so I would assume typescript inferencing would have determined the type from the argument's base.
Example code:
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'))
What I'd like to do is the first execute call and have typescript infer the correct return value, which is string in this case based on what GetSomethingByIdCommand was implemented from.
I've tried playing around with conditional types but not sure if this is a solution or how to apply it.
ICommand<T>interface in regards to howTis used. Because of that, yourGetSomethingByIdCommandclass also implicitly implementsICommand<number>(for example). Indeed it seems that the class is an implementation ofICommand<T>for any typeT. Given that, how is TypeScript to choose which type to infer?GetSomethingByIdCommandimplicitly implementICommand<number>when it explicitly implementsICommand<string>? Can you elaborate?