Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new instance of type in Typescript?

Tags:

typescript

I want to define the type explicitly and then create its instance. The following code explains the problem

import * as Immutable from "immutable";

// this works.
let map = new Immutable.Map<string, number>();

// neither works below.
type MapType = Immutable.Map<string, number>;
let map = new MapType();
let map = new MapType;
let map = MapType();
like image 924
nakajuice Avatar asked Sep 03 '25 01:09

nakajuice


1 Answers

When you define a type it's for compilation time only, it won't be part of the compiled js file, so new MapType can not work (because there's no such thing as MapType in the js).

You can do this:

let ctor = Immutable.Map;
let map = new ctor<string, number>();

or this:

let ctor: { new(): Map<string, number> } = Immutable.Map;
let map = new ctor();

In both cases the ctor is not a type but an actual variable, something that isn't removed by the compiler, but the compiler will translate this:

let ctor: { new(): Map<string, number> } = Immutable.Map;

into this:

let ctor = Immutable.Map;
like image 116
Nitzan Tomer Avatar answered Sep 13 '25 21:09

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!