I wonder if it is possible to determine the type of an object in typescript. Please consider the example below:
type T = [number, boolean];
class B {
foo: T = [3, true];
bar(): boolean {
return this.foo instanceof T;
}
}
The typeof operator does not seem to be a solution, neither does instanceof.
Short answer
(Almost) all type information are removed after compilation, and you can't use instanceof
operator with an operand (T
in your example) that does not exist at runtime.
Long answer
An identifier in TypeScript could belong to one or more of the following groups: type, value, namespace. What gets emitted as JavaScript is identifiers in the group of value.
Thus runtime operators only works with values. So if you want to do runtime type checking of the value of foo
, you'll need to do the hard work yourself.
See the Declaration Merging section of the TypeScript Handbook for more information.
To add to @vilcvane's answer: types
and interfaces
disappear during compilation, but some class
information is still available. So, for example, this doesn't work:
interface MyInterface { }
var myVar: MyInterface = { };
// compiler error: Cannot find name 'MyInterface'
console.log(myVar instanceof MyInterface);
But this does:
class MyClass { }
var myVar: MyClass = new MyClass();
// this will log "true"
console.log(myVar instanceof MyClass);
However, it's important to note that this kind of test can be misleading, even when your code compiles with no errors:
class MyClass { }
var myVar: MyClass = { };
// no compiler errors, but this logs "false"
console.log(myVar instanceof MyClass);
This makes sense if you look at how TypeScript is generating the output JavaScript in each of these examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With