Typescript: Allow Map<K,V> inline typing

Created on 29 Sep 2018  路  7Comments  路  Source: microsoft/TypeScript

Today

const map: {
  [name: string]: string[];
} : {
  key: ["A", "B"]
}

Tomorrow

const map: Map<string, string[]> :  {
  key: ["A", "B"]
}
Declined

All 7 comments

Huh? { [name: string]: string[]; } (string-indexable object) and Map<string, string[]> (ES6 Map object) are different things. To create a Map<string, string[]> equivalent to your example, you would use:

const map: Map<string, string[]> = new Map([["key", ["A", "B"]]]);

I don't even know exactly what the proposal here is, but I'm fairly certain that neither today nor tomorrow will ever come.

I think OP is looking for Record<K,V>

The notation I have in "tomorrow" can be seen in Dart and Bolt. It's very easy to read and write.

@lukepighetti Are you proposing that Map<string, string[]> be interpreted as the type of a string-indexable object (which we can't do because that syntax is already taken for the type of an ES6 map) or that { key: ["A", "B"] } be an initializer for an ES6 map (which would be a runtime feature outside the design goals of TypeScript)?

I'm proposing that there be an easier way to specify the type of values in an object. The only alternative syntax I am personally aware of is Map which I am familiar with from both Dart and Bolt.

In Dart if you're creating an object with keys as strings and values as booleans it looks like this

Map<String, boolean> myObject = {
  "key": true
}

In bolt it would be

type MyObject is Map<String, Boolean>

In Typescript, as far as I can tell (I am new to it), it is:

const myObject: {
  [name: string]: boolean;
} = {
  key: true
}

It would be nice if it was more succinct, like

const myObject: Map<String, Boolean> = {
  key: true
}

Hello, I have just investigated Record<K,V> and have found it to be exactly what I am looking for. Thank you all for the help.

Was this page helpful?
0 / 5 - 0 ratings