Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript generic interface function argument type inference error

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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> {
        …
    }
    …
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading