Reputation: 371
Better explain with example let's say I have :
class Model{
property1: number;
property2: number;
}
let model= new Model;
When I do
model["property1"]="sdaef" // Good ! typescript checks and know it should be number and give error
var test = model.nonExistingProp // throws error since the property does not exist which is good
Now the problem
var test = model["nonExistingProp"]; // NO ERRORS ??
I'm wondering since it is smart enough to know the properties from strings (associative array) and their types why does not throw error like previous example and say nonExistingProp, is there a way to force this kind of type checking on associative array since it already knows the properties and did the check for the type like first example ??
Thanks
Upvotes: 0
Views: 515
Reputation: 23443
TypeScript is smart enough, but this is a legacy feature for when indexing into an object was used as a form of getting around the type-checker.
However, if you use --noImplicitAny
(in addition to the other --strict
flags), you'll get safer checking and TypeScript will give an error on that expression.
For the record, flags the team has placed under the --strict
flag are things that the team believes will give you a much better experience in editing & error checking.
Upvotes: 1