Reputation: 1709
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
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