Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Last active October 20, 2023 20:17
Show Gist options
  • Save cgcardona/e8dff7ccfd9e021f914ce82f4a696be1 to your computer and use it in GitHub Desktop.
Save cgcardona/e8dff7ccfd9e021f914ce82f4a696be1 to your computer and use it in GitHub Desktop.

When you have a type which is an array of objects you can access the object's properties by using the dot notation. For example:

let foo = {
  arrKey: [{key: "value"}]
}

foo.arrKey[0].key // "value"

However, if you have an array of strings and objects then you'll need to use the bracket notation. For example:

let foo = {
  arrKey: [
    "first item",
    {key: "value"}
  ]
}

foo.arrKey[1].key 
// ERROR
// Property 'key' does not exist on type 'string | { key: string; }'.
// Property 'key' does not exist on type 'string'.ts(2339)

foo.arrKey[1]["key"] // "value"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment