I am using a custom type declared in TypeScript:
export type CustomType = {
id: number;
name: string;
optionA: boolean;
optionB: boolean;
// dozens more boolean options...
};
I want to refer to this later with a variable rather than a known-at-compile-time fixed string, like this:
const customObject: CustomType = callApi();
for(keyName : possibleKeys) { // possibleKeys contains "optionA" and "optionB"
if(customObject[keyName]) {
// do stuff
}
}
TypeScript says I can't do this, because
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'CustomType'.
The type itself is fine, as the following shows
console.log(customObject.optionA); // works
console.log(customObject["optionA"]); // works
const keyName = "optionA";
console.log(customObject[keyName]); // fails
I've found multiple resources for using variable keys to set data, but not much for getting data. I did try declaring an index signature but got numerous syntax errors (maybe because it's a type and not a plain old object?).
I made a fiddle demonstrating the above. Surprisingly, the log output shows that the code does work, even though it reports an error. My real build pipeline won't allow code with errors, though. How can I get around this?