Reputation: 289
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.
Upvotes: 22
Views: 26395
Reputation: 7630
You can use user-defined type guard for that. See this article for more details.
As for your code, here is the function you can define to check if your object is a T
:
type T = [number, boolean];
const isT = (value: any): value is T =>
Array.isArray(value) &&
typeof value[0] === 'number' &&
typeof value[1] === 'boolean';
Then use it this way:
const foo = [3, true];
console.log(isT(foo)); // true
const bar = 3;
console.log(isT(bar)); // false
Here is a simple DEMO to demonstrate this.
Upvotes: 1
Reputation: 12413
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.
Upvotes: 15
Reputation: 12814
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);
Upvotes: 7