我在typescript中创建了一个类,它的属性是ES6 (ECMAscript 2016) Map,如下所示:

class Item {
  configs: ????;
  constructor () {
    this.configs = new Map();
  }
}

我如何在typescript中声明一个ES6 Map类型?


当前回答

你可以在Typescript类中创建一个Map,如下所示

export class Shop {
  public locations: Map<number, string>;

  constructor() {
   // initialize an empty map
   this.locations= new Map<number,string>();
  }

   // get & set functions
   ........
}

其他回答

最起码:

tsconfig:

 "lib": [
      "es2015"
    ]

如果你想要IE < 11支持,安装一个polyfill如https://github.com/zloirock/core-js: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

见评论:https://github.com/Microsoft/TypeScript/issues/3069#issuecomment-99964139

TypeScript does not come with built in pollyfills. it is up to you to decide which pollyfill to use, if any. you can use something like es6Collection, es6-shims, corejs..etc. All the Typescript compiler needs is a declaration for the ES6 constructs you want to use. you can find them all in this lib file. here is the relevant portion: interface Map<K, V> { clear(): void; delete(key: K): boolean; entries(): IterableIterator<[K, V]>; forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V; has(key: K): boolean; keys(): IterableIterator<K>; set(key: K, value?: V): Map<K, V>; size: number; values(): IterableIterator<V>; [Symbol.iterator]():IterableIterator<[K,V]>; [Symbol.toStringTag]: string; } interface MapConstructor { new <K, V>(): Map<K, V>; new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>; prototype: Map<any, any>; } declare var Map: MapConstructor;

不确定这是否是官方的,但这在typescript 2.7.1中为我工作:

class Item {
   configs: Map<string, string>;
   constructor () {
     this.configs = new Map();
   }
}

在简单的Map<keyType, valueType>

是地图现在可在typescript..如果你查看lib.es6.d.ts,你会看到这样的界面:

interface Map<K, V> {
  clear(): void;
  delete(key: K): boolean;
  forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void,thisArg?: any): void;
  get(key: K): V | undefined;
  has(key: K): boolean;
  set(key: K, value: V): this;
  readonly size: number;} 

它伟大的使用作为一个字典的字符串,对象对..唯一的烦恼是,如果你用它来赋值其他地方的Map.get(键)IDE像代码给你的问题可能是未定义的..而不是创建一个变量的定义检查..简单地转换类型(假设您确定映射具有键-值对)

class myclass {
   mymap:Map<string,object>
   ...
   mymap = new Map<string,object>()
   mymap.set("akey",AnObject)
   let objectref = <AnObject>mymap.get("akey")

我如何在typescript中声明一个ES6 Map类型?

您需要目标——模块es6。这是不幸的,你可以在这里提出你的关注:https://github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111