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

Time:02-26

How can I set the key of a function returned object to the value of it's parameter?

I have the following:

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
  };
};

I'm trying to make an autocomplete with the value returned as key:

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

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

I've done before, I just don't remember how.

CodePudding user response:

This seems to do the trick:

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

  • Related