Home > Enterprise >  How to define the interface for an array in react and typescript
How to define the interface for an array in react and typescript

Time:09-26

I have a variable called data, which is an array that contains a function and an object. I want to define a model for this instead of using any, but unfortunately I don't know how, thank you for your help.

interface person {
  name: string;
  age: number;
}
interface data {
  // how do i write ?
  person: ;
  handleShowPerson: ;
}
export default function App() {
  const person: person = { name: "nil", age: 30 };
  const handleShowPerson = ({ name, age }: person) => (
    <h1>
      My name is {name} and I am {age} years old`)
    </h1>
  );
  const data: data = [person, handleShowPerson];
}

CodePudding user response:

As you want your data to be an array, you can do the following:

interface Person {
  name: string;
  age: number;
}

// First element of the array will be of type `Person`
// Second element will be a function that takes in `Person` as argument and returns JSX
// This sort of type definition is called a `Tuple` in typescript
type Data = [Person, (person: Person) => JSX.Element]

export default function App() {
  const person: Person = { name: "nil", age: 30 };
  const handleShowPerson = ({ name, age }: Person) => (
    <h1>
      My name is {name} and I am {age} years old`)
    </h1>
  );
  const data: Data = [person, handleShowPerson];
}

CodePudding user response:

Arrays can be defined by passing [] after the interface or type. So in this example the type becomes:

interface person {
  name: string;
  age: number;
}
interface data {
  person: ;
  handleShowPerson: ;
}[]
  • Related