I am trying to ensure that the return object from a function in TypeScript only allows keys that correspond to string values present in an array passed as an argument to the function. The returned object should contain a subset of keys from a list of valid strings based on the input array. I am struggling with referencing the actual values provided to 'myArr'.
declare type ListOfStrings = 'apple' | 'banana' | 'car';
function doSomething(myArr: ListOfStrings[]) {
const returnObj: { [Properties in ListOfStrings]?: number } = {};
for (const entry of myArr) returnObj[entry] = Math.random();
return returnObj;
}
const finalObj = doSomething(['banana', 'car']);
console.log(finalObj.apple); // This does not generate a TypeScript error, which is what I want help with.
Any advice would be greatly appreciated!