typescript - return 键等于输入字符串文字的对象

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

如何实现下面的'createCounter'功能?

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

谢谢

您可以通过为 key 参数指定泛型来实现。这是具有正确行为的代码:

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