Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript and type aliases

As I know TypeScript allows to create aliases for any types. Such as:

type MyNum = number;
var y: MyNum;
y = 33; // it's ok

but the followong code is not valid:

type MyType = Object;
const dt = new MyType(); // here is an error: 'MyType only refers to a type, but is being used as a value here'

Where am I wrong and how could I create instance of MyType?

like image 821
Pupkin Avatar asked Mar 09 '23 06:03

Pupkin


1 Answers

Type aliases are only for compile time, they are not getting translated into the compiled javascript code.

Your first code compiles to:

var y;
y = 33;

As you can see, there's nothing here about MyNum.

However, in your 2nd code snippet you're trying to use MyType as a value and not just as a type.
The compiler won't allow that because at runtime MyType isn't present as it compiles to:

var dt = new MyType();

Type aliases, just like interfaces (and types in general) are used for compilation only, so you cannot use them as values.


Edit

To create an instance of MyType, in this case:

const dt1: MyType = {};
const dt2: MyType = new Object();
const dt3: MyType = Object.create({});
like image 177
Nitzan Tomer Avatar answered Mar 20 '23 13:03

Nitzan Tomer