Eugeny89
Eugeny89

Reputation: 3731

Angular & typescript: using function argument as a type

Consider the following type

export type SomeToken<K extends string, V = any> = {
    [key in K]: V;
} & {
    created_at: Date;
    created_by_user: string;
};

usually K is a single string (e.g. K = 'token_a'). These tokens are loaded with the following method

public getToken<TokenId extends string>(token_id: string): Observable<SomeToken<TokenId>> {
    return this.http.get<SomeToken<TokenId>>(ENDPOINT_URL + '/' + token_id);
}

To call getToken I need to do something like getToken<'token_id'>('token_id'). token_id is repeated twice. Is there a way to avoid it?

Upvotes: 1

Views: 56

Answers (1)

jcalz
jcalz

Reputation: 327624

In your code, there's no relationship between the generic type parameter T (renamed from TokenId) and the type of the token_id parameter, which is just string... so if you want both to be the same type you need to specify it twice.

If, instead, you want the compiler to infer T from the value you pass in as the token_id parameter, you need to give token_id the type T:

public getToken<T extends string>(token_id: T): Observable<SomeToken<T>> {
    return this.http.get<SomeToken<T>>(ENDPOINT_URL + '/' + token_id);
}

Then things work as desired:

const t = new WhateverYourClassNameIs().getToken("token_id");
// const t: Observable<SomeToken<"token_id", any>>

Playground link to code

Upvotes: 1

Related Questions