Programming

Typescript의 ES6 맵

procodes 2020. 7. 5. 21:19
반응형

Typescript의 ES6 맵


ES6 (ECMAscript 2016) Map 속성을 가진 typescript에서 클래스를 만들고 있습니다.

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

typescript에서 ES6 Map 유형을 어떻게 선언합니까?


편집 (2019 년 6 월 5 일) : "TypeScript는 Map기본적으로 지원합니다"라는 아이디어 는 여전히 유효하지만 버전 2.1 TypeScript는라는 것을 지원하기 때문 Record입니다.

type MyMapLikeType = Record<string, IPerson>;
const peopleA: MyMapLikeType = {
    "a": { name: "joe" },
    "b": { name: "bart" },
};

불행히도 첫 번째 일반 매개 변수 (키 유형)는 여전히 완전히 존중되지 않습니다. string유형이 있더라도 peopleA[0](a number) 와 같은 것이 여전히 유효합니다.


편집 (2016 년 4 월 25 일) : 아래 답변은 오래되었으며 최상의 답변으로 간주해서는 안됩니다. TypeScript는 이제 "기본적으로"맵을 지원하므로 출력이 ES6 일 때 ES6 맵을 사용할 수 있습니다. ES5의 경우 폴리 필을 제공하지 않습니다. 직접 삽입해야합니다.

자세한 내용은 아래의 mohamed hegazy의 답변을 참조하십시오 . 더 현대적인 답변이나 짧은 버전의 경우이 레딧 의견 .


1.5.0 베타 버전에서 TypeScript는 아직 지도를 지원하지 않습니다 . 아직 로드맵의 일부가 아닙니다 .

현재 최상의 솔루션은 키와 값이 입력 된 객체입니다 (해시 맵이라고도 함). 유형 키가 있고 유형 string값이 있는 객체 의 경우 number:

var arr : { [key:string]:number; } = {};

그러나 몇 가지주의 사항 :

  1. 키는 유형 만 가능 string하거나number
  2. 숫자 / 문자열은 여전히 ​​상호 교환이 가능하므로 (값만 적용됨) 실제로 키 유형으로 사용하는 것은 중요하지 않습니다.

위의 예에서

// OK:
arr["name"] = 1; // String key is fine
arr[0] = 0; // Number key is fine too

// Not OK:
arr[{ a: "a" }] = 2; // Invalid key
arr[3] = "name"; // Invalid value

https://github.com/Microsoft/TypeScript/issues/3069#issuecomment-99964139의 의견 참조

TypeScript는 내장 된 pollyfill과 함께 제공되지 않습니다. 어떤 폴리 필 필지를 사용할지 결정하는 것은 당신에게 달려 있습니다. es6Collection , es6-shims , corejs ..etc 와 같은 것을 사용할 수 있습니다 . Typescript 컴파일러에 필요한 것은 사용하려는 ES6 구문에 대한 선언입니다. 이 lib 파일 에서 모두 찾을 수 있습니다 .

관련 부분은 다음과 같습니다.

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;

예를 들면 다음과 같습니다.

this.configs = new Map<string, string>();
this.configs.set("key", "value");

데모


예 Map은 이제 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;} 

Its great to use as a dictionary of string,object pairs.. the only annoyance is that if you are using it to assign values elsewhere with Map.get(key) the IDE like Code gives you problems about being possible undefined.. rather than creating a variable with an is-defined check .. simply cast the type (assuming you know for sure the map has the key-value pair)

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

How do I declare an ES6 Map type in typescript?

You need to target --module es6. This is misfortunate and you can raise your concern here : https://github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111


As a bare minimum:

tsconfig:

 "lib": [
      "es2015"
    ]

and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map


Typescript does not yet support Map.

ES6 Compatibility Table


With the lib config option your are able to cherry pick Map into your project. Just add es2015.collection to your lib section. When you have no lib config add one with the defaults and add es2015.collection.

So when you have target: es5, change tsconfig.json to:

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

Not sure if this is official but this worked for me in typescript 2.7.1:

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

In simple Map<keyType, valueType>


Add "target": "ESNEXT" property to the tsconfig.json file.

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

참고URL : https://stackoverflow.com/questions/30019542/es6-map-in-typescript

반응형