Typescript: Interfaces in connection types cause instance errors

I tried in the last hour, and I did not find a good answer or explanation of my problem.

I have a member variable defined as a union type, primitive (number) or interface (KnockoutObservable), and I cannot use typeof or typeof types without creating an error. I am using VS2013 update 4 with Typescript 1.4. I gave some examples to demonstrate the problem:

class foo { foo() {} } class bar { bar() {} } interface baz { baz(); } // This case breaks var var1: number|foo; if (typeof var1 === "number") { var1 = 5; } // Generates error "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." else if (var1 instanceof foo) { var1.foo(); } // This also breaks, same error as above if (var1 instanceof number) { var1 = 5; } else if (var1 instanceof foo) { var1.foo(); } // This case works var var2: foo|bar; if (var2 instanceof foo) { var2.foo(); } else if (var2 instanceof bar) { var2.bar(); } // This case breaks as well var var3: foo|baz; if (var3 instanceof foo) { var3.foo(); } // Generates error: "Cannot find name 'baz'." else if (var3 instanceof baz) { var3.baz(); } 

My question is: why are cases 1 and 3 interrupted? We create KnockoutJS components where the parameter can be observable or primitive. Since KnockoutObservable is an interface, it pretty much closes the possibility of using union types in our template; if we want the parameter to be either, we must return to using "any".

Some of the things I found about this (e.g. here ) seem to imply that this is fixed in 1.5. Can someone give me an assessment of this?

+6
source share
1 answer

Note that assigning a variable anywhere in the function body disables the type of this variable, so I removed assignments from this example.

Basically, there is a case that works as expected, a case that should work, but doesn't work, and a case that doesn't work, because there is no runtime information for the interfaces. instanceof is a JavaScript statement that checks the prototype chain of an object, not the TypeScript construct for type operations.

  var var1: number|foo; // OK if (typeof var1 === "number") { } // Bug #2775 // https://github.com/Microsoft/TypeScript/issues/2775 if (var1 instanceof foo) { } if (var1 instanceof number) { } // OK var var2: foo|bar; if (var2 instanceof foo) { } if (var2 instanceof bar) { } // TypeScript does not have reflection; there is no // value 'baz' to 'instanceof' at runtime. if (var3 instanceof baz) { var3.baz(); } 

The error in x instanceof number also intentional; no runtime value number . You might be tempted to write x instanceof number ; this would be a mistake ( 42 instanceof Number is false , not true ).

+2
source

Source: https://habr.com/ru/post/985298/


All Articles