Reputation: 36621
Is there an option available to force the Typescript compiler to recognize that requesting a property value from a generic object might be undefined
if the object doesn't contain that property.
I want that the following code snippet fails to compile:
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"];
because the type of valueOrUndefined
should be string | undefined
and not string
.
The compiler correctly detects this problem when the key is a type:
type CustomType = "Option1" | "Option2";
const keyFromTypeValueMap: {[P in CustomType]?: string} = {}
//The compiler correctly complains about the next line
const secondValueOrUndefined: string = keyFromTypeValueMap["Option1"];
The problem is that I have some of these objects where I don't know all the possible keys up front, so switching to a type is not a viable workaround.
Link to the Typescript Playground with this code
Upvotes: 0
Views: 220
Reputation: 51142
The behaviour you want is that of the noUncheckedIndexedAccess
flag, which you can enable on the command-line or in your tsconfig.json
file.
The reason the compiler gives you string | undefined
in the second example is because your type uses the ?
syntax for an optional property; you can do the same like {[key in string]?: string}
, if you want a workaround that doesn't involve changing the project configuration. Note that this is a mapped type, not an index signature.
Upvotes: 1