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

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

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


当前回答

最起码:

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

其他回答

在tsconfig中添加"target": "ESNEXT"属性。json文件。

{
    "compilerOptions": {
        "target": "ESNEXT" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    }
}

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

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

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

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

使用库配置选项,您可以樱桃选择映射到您的项目。只需添加es2015。集合到您的lib部分。当你没有库配置时,添加一个默认库,并添加es2015.collection。

所以当你有target: es5时,改变tsconfig。json:

"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],

最起码:

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;