如何在 Typescript 中定义数字-> 字符串字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15462799/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:48:43  来源:igfitidea点击:

how do I define a number->string dictionary in Typescript?

typescript

提问by KallDrexx

I'm playing with Typescript and converting over a small library over to it from Javascript. In one area of the code there was a statically defined mapping of friendly key name to their keycode. The original code looked like:

我正在使用 Typescript 并将一个小型库从 Javascript 转换为它。在代码的一个区域中,有一个静态定义的友好密钥名称到它们的密钥代码的映射。原始代码如下所示:

keys: { "Backspace": 8, "Tab": 9, "Enter": 13, ....etc.. };

I defined this in typescript via:

我通过以下方式在打字稿中定义了这一点:

static keys: { [name: string]: number; } = { "Backspace": 8, "Tab": 9, "Enter": 13, ... etc.. };

This seems to work fine, however another part of the code uses the opposite mapping:

这似乎工作正常,但是代码的另一部分使用相反的映射:

    chars: {8:"Backspace",9:"Tab",13:"Enter", ...etc... };

So I tried to do the same type of definition in typescript that I did previously:

因此,我尝试在打字稿中进行与我之前所做的相同类型的定义:

chars: { [code: number]: string; } = { 8: "Backspace", 9: "Tab", 13: "Enter", ...etc.. };

This fails to compile with the following error:

这无法编译并出现以下错误:

Cannot convert '{ 0: string; 1: string; 2: string; 4: string; 8: string; 9: string; : string; }' to '{ [name: number]: string; }': Index signatures of types '{ 0: string; 1: string; 2: string; 4: string; 8: string; 9: string; : string; }' and '{ [name: number]: string; }' are incompatible

无法转换 '{ 0: string; 1:字符串;2:字符串;4:字符串;8:字符串;9:字符串;: 细绳; }' 到 '{ [名称:编号]:字符串;}': '{ 0: string; 类型的索引签名 1:字符串;2:字符串;4:字符串;8:字符串;9:字符串;: 细绳; }' 和 '{ [名称:编号]:字符串;}' 不兼容

How do I define this mapping in Typescript?

我如何在 Typescript 中定义这个映射?

回答by MiMo

The problem is that in JavaScript - and hence in TypeScript - the keys of an object literal are always strings, and so it cannot be assigned to a variable with a number indexer.

问题在于,在 JavaScript 中——因此在 TypeScript 中——对象字面量的键始终是字符串,因此不能将其分配给带有数字索引器的变量。

An object with a number indexer is an array - and so you have to do this:

带有数字索引器的对象是一个数组 - 所以你必须这样做:

var chars: string[] = [];
chars[8]= "Backspace";
chars[9]= "Tab";
chars[13] = "Enter";

回答by Doug

Here's a library called Classical.js* that may help you accomplish this and similar problems. It defines, among other things, a doubly generic dictionary. For your use case, the code would look like this:

这是一个名为 Classical.js*的库,可以帮助您解决此问题和类似问题。除其他外,它定义了双重通用字典。对于您的用例,代码如下所示:

import c = Classical.Collections;

var keys = new c.Dictionary<string, number>();
keys.add("Backspace", 8);
keys.add("Tab", 9);
keys.add("Enter", 13);
//etc...

keys.getValue("Backspace"); //8
keys.getValue("Tab"); //9
keys.getValue("Enter"); //13
//etc...

Dictionary<TKey, TValue> works with all types of objects and doesn't have issues with name collisions such as keys named 'constructor'.

Dictionary<TKey, TValue> 适用于所有类型的对象,并且不会出现名称冲突问题,例如名为“构造函数”的键。

For the opposite mapping you could either construct the inverse dictionary or query the current one like so:

对于相反的映射,您可以构建逆字典或查询当前字典,如下所示:

keys.query().single(pair => pair.key === 8).value; //"Backspace"
keys.query().single(pair => pair.key === 9).value; //"Tab"
keys.query().single(pair => pair.key === 13).value; //"Enter"
//etc...

If you'd like to give it a try, visit Classical, open up the bin folder and add classical.js and classical.d.ts to your project.

如果您想尝试一下,请访问Classical,打开 bin 文件夹并将 classic.js 和 classic.d.ts 添加到您的项目中。

Hope that helps.

希望有帮助。



* I am one of the developers on the classical team

* 我是经典团队的开发者之一

回答by basarat

Indeed js internally only has string based indices (with Array being different from {}) but string / number conversion is stable in js :

实际上,js 内部只有基于字符串的索引(Array 与 {} 不同),但字符串/数字转换在 js 中是稳定的:

var x = {0 : "asdf",1:"bb"} 
alert(x[0])
alert(x[1])

I think typescript should support it as well and created a work item you can vote on: http://typescript.codeplex.com/workitem/832

我认为打字稿也应该支持它并创建了一个您可以投票的工作项目:http: //typescript.codeplex.com/workitem/832