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
>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