Issue
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.
Solution
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.
Answered By – vilicvane
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0