How can I make the Typescript compiler recognize that accessing a property value from a generic object may be undefined
if the object does not have that property?
I need the following code snippet to fail during compilation:
const keyValueMap: {[key: string]: string} = {};
keyValueMap["foo"]="bar";
//I want the next line to cause a compile error
//because the type should be string | undefined
const valueOrUndefined: string = keyValueMap["someKey"];
This is because the type of valueOrUndefined
should be string | undefined
and not just string
.
The compiler correctly identifies this issue when the key is a specific type:
type CustomType = "Option1" | "Option2";
const keyFromTypeValueMap: {[P in CustomType]?: string} = {}
//The compiler correctly points out the error in the next line
const secondValueOrUndefined: string = keyFromTypeValueMap["Option1"];
The challenge arises when dealing with objects where all possible keys are not known upfront, making switching to a type an impractical solution.