3

I understand the normal Map<string, string> format. But i have seen some people use { [k: string]: string } for the same use case?

Are they same or different? i cannot find a proper documentation regarding it's use cases.

is it possible to convert one to another?

Does it have to do something with the object de-structuring ?

Tilak Raj
  • 1,369
  • 5
  • 31
  • 64

1 Answers1

4

In a basic sense, { [k: string]: string } is for an object, and Map<string, string> is for a Javascript Map primitive, which is not exactly the same.

For example, you could do Map<object, string>, because a Map can use an object as a key. However, { [k: object]: string } immediately throws an error, because javascript objects cannot use objects as their keys.

This does not have to do with destructuring, but rather with the difference between a standard javascript Object and a Map. I'm not sure what you mean when you say you've seen them used interchangeably, as this typescript playground throws an error when mixing them up.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • @Code-Apprentice wut? No, an object. – Robo Robok Apr 30 '21 at 18:25
  • 1
    @Code-Apprentice Ummm...no? `{ [key: type]: type }` is how we notate an object's key's type in typescript....in this case, `[]` is not an array, but a dynamically accessed object key. – Seth Lutske Apr 30 '21 at 18:27
  • Oh gotcya...the brackets confused me there. – Code-Apprentice Apr 30 '21 at 18:28
  • so saying `{}` and `{abc: test }` would be same? i mean if i defined something as types as `{ [k:string]:string}` , could i defined an empty one as `let abc = {}`. Since it's an object? – Tilak Raj Apr 30 '21 at 18:43
  • Yes that's fine, `{ [k:string]: string }` allows for empty objects, so long as any entries in that object that occur have string values. [like this](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMoHsC2EDyAjAK2QG8AoZZAbQGsIBPALmQGcwpQBzAXSdfZA4BuUgF9SpBOhCtkmOvgJMM2BcgC8JMaTkKAdAAsIAGyPp1yAOSGT6C9vmFdHdOgAmeOig0AmIA) – Seth Lutske Apr 30 '21 at 18:48
  • i am not sure, i have one object property of such type but when de-structuring it back to some object gives me `undefined` – Tilak Raj Apr 30 '21 at 18:48
  • `let { attachments } = resource.current.aws.policies.attachments; const policies = {}; console.log(resource.current) console.log("attachments", attachments);` output is : `e (object) and attachments as {}` while second line shows `undefined`. – Tilak Raj Apr 30 '21 at 18:50
  • 1
    Its hard to say exactly is going on in your specific use case, but are you sure you want `let { attachments } = resource.current.aws.policies.attachments`? Shouldn't that be `let { attachments } = resource.current.aws.policies`? – Seth Lutske Apr 30 '21 at 18:52