0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

by the way can i force strict check only for that file ?
i thought there might be something like ts-check flag that's added to js files that can be applied locally

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.