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?
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.
To create an instance of MyType
, in this case:
const dt1: MyType = {};
const dt2: MyType = new Object();
const dt3: MyType = Object.create({});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With