Robin
Robin

Reputation: 36621

Typescript compiler doesn't recognize that an object entry might not exist

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

Answers (1)

kaya3
kaya3

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

Related Questions