[基本打字稿]:将函数返回对象的键设置为它的参数值

[Basic typescript]: set the key of a function returned object to the value of it's param

如何将函数返回对象的键设置为它的参数值?

我有以下内容:

const makeCache = <A, T extends string>(name: T, base = {}) => {
  const cache = base;

  return {
    [name]: cache,
  } as {
    [key in keyof T]: typeof cache; // this didn't work
    // [key in typeof name]: typeof cache; // this didn't work
    // [key in keyof typeof name]: typeof cache; // this didn't work
    // [key: typeof name]: typeof cache; // this didn't work
  };
};

我正在尝试使用作为键返回的值进行自动完成:

makeCache('root').root // ok
makeCache('hello').hello // ok

makecache('error').notError // error!

以前做过,只是不记得怎么做了。

这似乎可以解决问题:

const makeCache = <A, T extends string>(name: T, base = {}) => {
  const cache = base;

  return {
    [name]: cache,
  } as {
    [key in typeof name]: typeof cache
  };
};

makeCache('error').error // bombs with notError

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgQwNYFMDCDgAsUwLwwA8AggDQwAqMKAHlCmACYQzQBOAlmAOYB8AFGARwUALkrkARggi4CAbwC+ASny8Y8gFAwYoSLGCYc+GNNkBuTdphsUUAK5swG6zoDaQkQF1xh7ClJrRRgZFx13VABPGC4YKEiABxQQADMYTxQfOMTktL8cIMtFS01EVAx-fgByFDY2EDYq5QA6Wvq2IA