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();
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;
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