Edshav
Edshav

Reputation: 396

How to use typescript generic type as an object key

function myFunc<T extends string>(key: T): Record<T, string> {
        return { [key]: 'asdf' };
    }

I get an error:

Type '{ [x: string]: string; }' is not assignable to type 'Record<T, string>'.ts(2322)

How to get rid of the error and enable auto-completion on the returned object?

P.S. Without using return { [key]: 'asdf' } as Record<T, string>

Upvotes: 0

Views: 47

Answers (1)

tenshi
tenshi

Reputation: 26324

Move the signature into an overload:

function myFunc<T extends string>(key: T): Record<T, string>;
function myFunc(key: string) {
    return { [key]: 'asdf' };
}

Playground

Upvotes: 2

Related Questions