Home > Enterprise >  Typescript generic interface function argument type inference error
Typescript generic interface function argument type inference error

Time:01-29

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!!

CodePudding user response:

The getById<T extends number | string>(id: T): Promise<SomeType> generic method is pretty pointless, that's more or less equivalent to just declaring a method of type getById(id: number | string): Promise<SomeType>.

I suspect what you actually want is

export interface BaseService<T extends number | string> {
    getById(id: T): Promise<SomeType>;
}
export class AService implements BaseService<number> {
//                                          ^^^^^^^^
    async getById(id: number): Promise<SomeType> {
        …
    }
    …
}
  • Related