Home > OS >  typescript - return an object with key equals to an input string literal
typescript - return an object with key equals to an input string literal

Time:03-15

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

CodePudding user response:

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

  • Related