简体   繁体   中英

Typescript generic map return value

I have a method that returns an Object which I use as a map to arrays of strings.
My problem is that I don't know how to define the return value using generics for type safety.
I thought about adding a new interface or class to represent a map, but I'd like to avoid that, given that Object itself is already a map.

Here's some example code that should shed some light on the problem:

getMap() : Object {
  return {
    1: [ 'a', 'b', 'c' ]
    2: [ 'd', 'e' ],
    3: [ ]
  }
}

I'd like to be able to define the return value of the method so that it's clear that it's a map of String[] or Array<String> , without the need to implement an artificially added Map interface.

Any thoughts ?

Like @Aleksey commented, { [key: number]: string [] } would do the job.

Further, there is a builtin type alias Record actually represents a map. { [key: number]: string[] } is equal to Record<number, string[]> . And if you want to support string keys as well, the type would be Record<number | string, string[]> Record<number | string, string[]> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM