1

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

1 Answer 1

1
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.