简体   繁体   中英

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.

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"},
]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM