1

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?

2
  • 2
    Please ask a single question per post. Which one of those two questions is primary? I assume it's the first one. If so, then the solution is to make token_id have the generic type instead of string, like public getToken<T extends string>(token_id: T): Observable<SomeToken<T>> {} . If that meets your needs I could write up an answer explaining; if not, what am I missing? Commented Oct 19, 2022 at 14:57
  • I've removed the second question. And yes, your answer is what I need, please write it up as an answer. Thank you! Commented Oct 19, 2022 at 19:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.