Phani
Phani

Reputation: 309

How to safely define a Array of Array in typescript with react

I do have an array of arrays full of objects for example as below

const array1: 
       any[] = 
            [
            {firstName: "John", lastName: "Doe"},
            {firstName: "Jane", lastName: "Doe"},
       ],
       [
            {firstName: "John", lastName: "Doe"},
       ],
       [
            {firstName: "Jane", lastName: "Doe"},
       ]
]

We do have a type restriction of using "any".

So would like to know what is the better way to define the type of array1.

Upvotes: 1

Views: 1842

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85152

Create an interface for the person objects (if you don't have one already), then use that

interface Person {
  firstName: string,
  lastName: string,
}

const array1: Person[][] = [[
  {firstName: "John", lastName: "Doe"},
  {firstName: "Jane", lastName: "Doe"},
], [
  {firstName: "John", lastName: "Doe"},
], [
  {firstName: "Jane", lastName: "Doe"},
]];

Upvotes: 3

Related Questions