TypeScript and enter aliases

As I know, TypeScript allows you to create aliases for any type. For instance:

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

but the following code is invalid:

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 mistaken and how can I create an instance of MyType?

+4
source share
1 answer

Typical aliases are for compile time only, they are not translated into compiled javascript code.

Your first code compiles to:

var y;
y = 33;

As you can see, there is nothing here MyNum.

However, in the second code snippet you are trying to use MyTypeas a value, and not just as a type.
The compiler will not allow this, because at runtime it is MyTypenot, since it compiles:

var dt = new MyType();

, ( ), , .


MyType, :

const dt1: MyType = {};
const dt2: MyType = new Object();
const dt3: MyType = Object.create({});
+7

Source: https://habr.com/ru/post/1675714/


All Articles