Javascript 打字稿中的 ES6 映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30019542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 Map in Typescript
提问by nicksrandall
I'm creating a class in typescript that has a property that is an ES6 (ECMAscript 2016) Map like so:
我在打字稿中创建一个类,它的属性是 ES6 (ECMAscript 2016) Map,如下所示:
class Item {
configs: ????;
constructor () {
this.configs = new Map();
}
}
How do I declare an ES6 Map type in typescript?
如何在打字稿中声明 ES6 Map 类型?
回答by zeh
EDIT (Jun 5 2019):While the idea that "TypeScript supports Mapnatively" is still true, since version 2.1 TypeScript supports something called Record.
编辑(2019 年 6 月 5 日):虽然“TypeScript 原生支持Map”的想法仍然正确,但因为 2.1 版 TypeScript 支持名为Record.
type MyMapLikeType = Record<string, IPerson>;
const peopleA: MyMapLikeType = {
"a": { name: "joe" },
"b": { name: "bart" },
};
Unfortunately the first generic parameter (key type) is still not fully respected: even with a stringtype, something like peopleA[0](a number) is still valid.
不幸的是,第一个泛型参数(键类型)仍然没有得到完全尊重:即使是一个string类型,像peopleA[0](a number)这样的东西仍然有效。
EDIT (Apr 25 2016):The answer below is old and should not be considered the best answer. TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6. For ES5, it does not provide polyfills; you need to embed them yourself.
编辑(2016 年 4 月 25 日):下面的答案是旧的,不应被视为最佳答案。TypeScript 现在“本地”支持 Maps,因此它只允许在输出为 ES6 时使用 ES6 Maps。对于 ES5,它不提供 polyfill;你需要自己嵌入它们。
For more information, refer to mohamed hegazy's answer belowfor a more modern answer, or even this reddit commentfor a short version.
有关更多信息,请参阅下面 mohamed hegazy 的答案以获得更现代的答案,或者甚至是简短版本的reddit 评论。
As of 1.5.0 beta, TypeScript does not yet support Maps. It is not yet part of the roadmap, either.
从 1.5.0 beta 开始,TypeScript 还不支持Maps。它也不是路线图的一部分。
The current best solution is an object with typed key and value (sometimes called a hashmap). For an object with keys of type string, and values of type number:
当前最好的解决方案是具有类型化键和值的对象(有时称为哈希图)。对于键为 typestring且值为 type 的对象number:
var arr : { [key:string]:number; } = {};
Some caveats, however:
但是,一些警告:
- keys can only be of type
stringornumber - It actually doesn't matter what you use as the key type, since numbers/strings are still accepted interchangeably (only the value is enforced).
- 键只能是类型
string或number - 实际上,您使用什么作为键类型并不重要,因为数字/字符串仍然可以互换接受(仅强制执行值)。
With the above example:
用上面的例子:
// 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
回答by mohamed hegazy
See comment in: https://github.com/Microsoft/TypeScript/issues/3069#issuecomment-99964139
见评论: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 没有内置的pollyfills。如果有的话,由您来决定使用哪种pollyfill。你可以使用像 es6Collection、 es6-shims、 corejs.. 之类的东西。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;
回答by Arnaud
回答by nphias
Yes Map is now available in typescript.. if you look in lib.es6.d.ts, you will see the interface:
是的 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)
它的伟大作为字符串的字典来使用,对象对..唯一的烦恼是,如果你正在使用它来分配值与别处Map.get(键)喜欢代码的IDE提供了有关是可能未定义的问题...而不是创建一个带有 is-defined 检查的变量 .. 只需转换类型(假设您确定地图具有键值对)
class myclass {
mymap:Map<string,object>
...
mymap = new Map<string,object>()
mymap.set("akey",AnObject)
let objectref = <AnObject>mymap.get("akey")
回答by basarat
How do I declare an ES6 Map type in typescript?
如何在打字稿中声明 ES6 Map 类型?
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
您需要针对--module es6. 这是不幸的,你可以在这里提出你的担忧:https: //github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111
回答by Nikos
As a bare minimum:
作为最低限度:
tsconfig:
配置:
"lib": [
"es2015"
]
and install a polyfill such as https://github.com/zltheitroadock/core-jsif you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
并安装一个填充工具如https://github.com/zltheitroadock/core-js如果你想IE <11支持:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /地图
回答by HolgerJeromin
With the lib config optionyour are able to cherry pick Map into your project. Just add es2015.collectionto your lib section. When you have no lib config add one with the defaultsand add es2015.collection.
使用lib 配置选项,您可以将 Map 挑选到您的项目中。只需添加es2015.collection到您的 lib 部分。当您没有 lib 配置时,添加一个默认值并添加es2015.collection.
So when you have target: es5, change tsconfig.json to:
所以当你有目标:es5 时,将 tsconfig.json 更改为:
"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],
回答by Jonas Tomanga
Not sure if this is official but this worked for me in typescript 2.7.1:
不确定这是否是官方的,但这在打字稿 2.7.1 中对我有用:
class Item {
configs: Map<string, string>;
constructor () {
this.configs = new Map();
}
}
In simple Map<keyType, valueType>
简单来说 Map<keyType, valueType>
回答by Logan Tegman
回答by Yas
Add "target": "ESNEXT"property to the tsconfig.jsonfile.
将"target": "ESNEXT"属性添加到tsconfig.json文件中。
{
"compilerOptions": {
"target": "ESNEXT" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
}
}

