Generic interface
export interface BaseService {
getById<T extends number | string>(id: T): Promise<SomeType>;
}
And, the implementation
export class AService implements BaseService {
async getById(id: number): Promise<SomeType> {
// logic
}
//Other functions will be implemented here
}
And, the error I am getting:
Property 'getById' in type 'AService' is not assignable to the same property in base
type 'BaseService'.
Type '(id: number) => Promise<SomeType>' is not assignable to type '<T extends
string | number>(id: T) => Promise<SomeType>'.
Types of parameters 'id' and 'id' are incompatible.
Type 'T' is not assignable to type 'number'.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.ts(2416)
Couple of things that I have tried:
getById<T extends number>(id: T): Promise<SomeType>; //This works, But I would have some methods with id type string
And,
getById<T>(id: T): Promise<SomeType>; //still compains
I have been following Documentation. But, haven't encountered any similar thing.
Would really appreciate any ideas or thoughts or any documentation!!
BaseEntityorSpeciesEntityare undefined, should be removed.getById<T extends number | string>(id: T)let's you capture a type used for the argumentidand use that type somewhere else, such as the return type of the method. But your return types do not depend onTat all. If you don't useTanywhere else, then you don't need it, and you're better off using the constraint as the argument type directly.sof typeBaseService(or any type thatextendsit), then you are allowed to calls.getById("hello")andTwill be inferred as"hello". The implementer ofgetById()does not get to decide thatTwill benumberor anything else. It seems you wantBaseServiceitself to be generic in the type ofid, like this; does that meet your needs? If so I could write up an answer; if not, what am I missing?