TSConfig
noPropertyAccessFromIndexSignature
This setting ensures consistency between accessing a field via the “dot” (obj.key
) syntax, and “indexed” (obj["key"]
) and the way which the property is declared in the type.
Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:
tsTry
interfaceGameSettings {// Known up-front propertiesspeed : "fast" | "medium" | "slow";quality : "high" | "low";// Assume anything unknown to the interface// is a string.[key : string]: string;}constsettings =getSettings ();settings .speed ;settings .quality ;// Unknown key accessors are allowed on// this object, and are `string`settings .username ;
Turning the flag on will raise an error because the unknown field uses dot syntax instead of indexed syntax.
tsTry
constsettings =getSettings ();settings .speed ;settings .quality ;// This would need to be settings["username"];Property 'username' comes from an index signature, so it must be accessed with ['username'].4111Property 'username' comes from an index signature, so it must be accessed with ['username'].settings .; username
The goal of this flag is to signal intent in your calling syntax about how certain you are this property exists.