Home > Mobile >  using generic class<T> type as value to matches with enum key
using generic class<T> type as value to matches with enum key

Time:10-09

I have this enum with my routes defined like below

export enum ApiPath {
    User = "/users",
    Property = "/properties",
     ...
}

For example, I call the GenericHttpClient with my interface User in another class.

How can I match my generic type with the enum key like below?

    export class GenericHttpClient<T> extends HttpClient {

       async findOne(args: { id: string }): Promise<T> {
       const url = ApiPath[T]; // this is not working 

       return await this.get<T>(`${url}/${args.id}`);
     }

    }

'T' only refers to a type, but is being used as a value here.

Is there an easy way to fix this ?

CodePudding user response:

You cannot use T as a value because T is a type, and types don't exist at runtime. But you can use a value of type T that exists as a property of your instance.

Additionally, enums aren't really designed for you pass around the key of the enum. Instead accept MyEnum and pass in a MyEnum.MyValue.


I'm assuming that you pass in the ApiPath value with the constructor of GenericHttpClient.

That would mean you need to do this:

export class GenericHttpClient<T extends ApiPath> {
    path: T

    constructor(path: T) {
        this.path = path
    }
}

const client = new GenericHttpClient(ApiPath.User)
// client is of type: GenericHttpClient<typeof ApiPath['User']>

Now T is set by the type of the path parameter of the constructor, and then that value is saved to the instance.

Now you can add a findOne() method this is very simply this:

    async findOne(args: { id: string }): Promise<T> {
        const url = this.path;
        return await this.get<T>(`${url}/${args.id}`);
    }

See playground

  • Related