Home > Back-end >  How to use typescript generic type as an object key
How to use typescript generic type as an object key

Time:10-15

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>

CodePudding user response:

Move the signature into an overload:

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

Playground

  • Related