Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeof/instanceof type alias

Tags:

typescript

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.

like image 453
Peter Avatar asked Mar 02 '16 11:03

Peter


2 Answers

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.

like image 106
vilicvane Avatar answered Sep 23 '22 01:09

vilicvane


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.

like image 32
Nathan Friend Avatar answered Sep 24 '22 01:09

Nathan Friend