最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript generic map return value - Stack Overflow

programmeradmin1浏览0评论

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 ?

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 ?

Share Improve this question asked Feb 17, 2019 at 11:40 ethanfarethanfar 3,77827 silver badges44 bronze badges 4
  • 4 How about { [key: number]: string[] }? Also it is remended to use object/string (lowercase), explanation here – Aleksey L. Commented Feb 17, 2019 at 11:53
  • 1 @AlekseyL. , I've been using number, boolean and string in all lowercase (didn't know why at the time), just Object stuck with me (probably from Java ...). I wasn't aware of this syntax as I'm new to TypeScript. Thanks a lot ! – ethanfar Commented Feb 17, 2019 at 16:15
  • @AlekseyL. what about Array<String> vs. String[] ? Same thing ? Is that for boxing as well ? – ethanfar Commented Feb 17, 2019 at 16:17
  • 1 You're wele! Regarding Array vs [] - there's no difference (as it not primitive), so Array<string> is the same as string[] – Aleksey L. Commented Feb 18, 2019 at 6:55
Add a ment  | 

1 Answer 1

Reset to default 5

Like @Aleksey mented, { [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[]>.

发布评论

评论列表(0)

  1. 暂无评论