Why doesn't TypeScript narrow down any type in this type?

The following example confuses me:

class MyClass
{
    public MyProp = "";
}

var object: any = null;

if (object instanceof MyClass)
    console.log(object.MyProp, object.NonExistant); // <-- No error, no intellisense

Why doesn't the type guardian give me the correct type in the checked context?

+4
source share
1 answer

Custom types of guards and instanceofType of protection does not narrow the types that are any(including union and intersection c any).

The only thing that will narrow down the anytype defender is to use validation typeofand validation for the primitive string, booland number:

var something: any;
if (typeof something === "string")
{
    something.NonExistant(); // <- Error, does not exist on `string`
    something.substr(0, 10); // <- Ok
}

typeof, function, object undefined, any, , .

, any , TS 2.0.

,

, -, , - , , , , . - any , , any, , .

, , , TypeScript any , .

, , object any, .

+3

All Articles