Michal Zimmermann

Pieces of knowledge from the world of web development.

Using mapped types to access object properties

4/6/2022
type Configuration = {
  'one': number;
  'two': string[];
  'three': () => void;
}

// ✅ right
const fn = (what: { [key in keyof Configuration ]: Configuration[key]}) => {
  if (what.one) {
    what.one.toFixed();
  }

  if (what.two) {
    what.two.slice(0, 1);
  }

  if (what.three) {
    what.three();
  }
}

// ❌ wrong
const fn2 = (what: Record<Key, Configuration[Key]>) => {
  if (what.one) {
    what.one.toFixed();
  }
}