[SOLVED] typescript – return an object with key equals to an input string literal

Issue

How to implement the following ‘createCounter’ function?

function createCounter(key: string) {
    return {[key]:0} // Note this doesn't work
}

const obj = createCounter('sum')
obj.sum += 20 // works
obj.prop = 0  // oops: no such property

Thanks

Solution

You can do this via specifying a generic for the key parameter. Here’s your code with the correct behavior:

function createCounter<K extends PropertyKey>(key: K): { [H in K]: Record<H, number> }[K] {
    return { [key]: 0 } as any; // a cast is sadly required because TS isn't smart enough
}

const obj = createCounter('sum')
obj.sum += 20 // works
obj.prop = 0  // oops: no such property

TypeScript Playground Link

Answered By – sno2

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *