Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to define object type with dynamic set of keys

Suppose I have a function that accepts an array of string as an argument and builds an object that has each of the array item as a key. Like this:

function buildObject(keys: string[]) {
  let obj = {};
  for (let i = 0; i < keys.length; i++) {
    obj[keys[i]] = i;
  }
  return obj;
}

Is it possible to define a return type for this function so that attempt to access object key that is not defined would result in compiler error?

const obj = buildObject(['a', 'b', 'b']);
console.log(obj.a) // OK
console.log(obj.d) // I want a compiler error here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make the keys array as readonly and then use the type of its values as keys for the result object.

function buildObject<T extends string>(keys: readonly T[]): Record<T, number> {
  let obj = {} as Record<T, number>;
  for (let i = 0; i < keys.length; i++) {
    obj[keys[i]] = i;
  }
  return obj;
}

const obj = buildObject(['a', 'b', 'b']);
console.log(obj.a) // OK
console.log(obj.b) // OK
console.log(obj.d) // Error

Playground link: https://tsplay.dev/wEY64w

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading