Sabbiu Shah
Sabbiu Shah

Reputation: 1709

How to make typescript to allow only the values from the array?

This is my helper function

type ReturnType = { [k1: string]: { [k2: string]: string } } ;
function createObject(arr: string[]) : ReturnType {
  const tempObj : ReturnType = {};
  arr.forEach((item) => {
    tempObj[item] = {
      x: `${item}-x`,
      y: `${item}-y`,
      z: `${item}-z`,
    };
  });

  return tempObj;
}

Now, I create a new object, using the helper function.

const myObj = createObject(['a', 'b', 'c']);

How do I modify my helper function, so that typescript generates error when the values are not from the given array.

myObj.a.x; // Correct
myObj.something.other; // must give error

Upvotes: 1

Views: 39

Answers (1)

Micah Zoltu
Micah Zoltu

Reputation: 7422

type Foo<T extends readonly string[]> = { [Key in T[number]]: { x: string, y: string, z: string } }
function createObject<T extends readonly string[]>(array: T): Foo<T> {
  const tempObj = {} as any
  array.forEach((item) => {
    tempObj[item] = {
      x: `${item}-x`,
      y: `${item}-y`,
      z: `${item}-z`,
    };
  });

  return tempObj;
}
const apple = createObject(['a', 'b', 'c'] as const)

Upvotes: 1

Related Questions