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:
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
How do I define this mapping in Typescript?
Use the String() object to convert a number to a string in TypeScript, e.g. const str = String(num) . When used as a function, the String object converts the passed in value to a primitive string and returns the result. Copied!
Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values.
To declare and initialize a dictionary in TypeScript, we can create a dynamic object type. const persons: { [id: string]: IPerson } = {}; persons["p1"] = { firstName: "jane", lastName: "smith" }; to set the persons variable to type { [id: string]: IPerson } .
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.
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";
Indeed js internally only has string based indices (with Array being different from {}) but string / number conversion is stable in 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With