1
type DocumentData = { [field: string]: any };
let data1: DocumentData = {4:3};

console.log(data1); //{4:3}

key is string type, value is any type, Doesn't it mean that the DocumentData type in the above code is the object type of the above type? I know Dart, so isn't it the Map<String, dynamic> type in Dart?

However, when I ran the above code on the site below, it seems that no error occurred. Am I misunderstanding something? https://playcode.io/1081552

As indicated above.As explained above, I can't grasp what kind of data structure the DocumentData type indicates.

Mike Johan
  • 25
  • 3
  • Why not use a JS `Map`? – Asplund Jan 20 '23 at 08:48
  • 1
    What is causing the confusion here? That number keys are allowed? – Tobias S. Jan 20 '23 at 08:55
  • It is by design. Indexing by a number is a subset of indexing by a string, so indexing by a number when a string would have been valid is also valid (Source: https://github.com/microsoft/TypeScript/issues/7660#issuecomment-200543029) – Legends Jan 20 '23 at 11:54

1 Answers1

0

Read this: What do square brackets mean where a field should be in typescript?

TL:DR DocumentData is an object with an indexable field.

So when you instantiate data1 with 4 as the key, 4 is a valid index.

Aric Kuter
  • 415
  • 3
  • 12
  • You tried passing a number where string is expected? See [fixed](https://www.typescriptlang.org/play?#code/C4TwDgpgBAIg9gYwK4FsIDtgwIbGwHgBUA+KAXigG8oBtAawhAC4oBnYAJwEt0BzAXRaEoAXwDcAWABQCOOnZQAJrmwBGFvGRpMOPPmzoQpCtQAsTAMyjJMuQuV4ATBsSoMWFfnbc+xqlHMAIgtA62kgA) – Aric Kuter Jan 20 '23 at 08:49
  • Thank you for your reply. I felt strongly that I needed to learn the basics of TypeScript. – Mike Johan Jan 23 '23 at 14:00