[英]How to define the interface for an array in react and typescript
I have a variable called data
, which is an array
that contains a function
and an object
.我有一个名为data
的变量,它是一个包含function
和object
的array
。 I want to define a model for this instead of using any
, but unfortunately I don't know how, thank you for your help.我想为此定义一个 model 而不是使用any
,但不幸的是我不知道如何,谢谢你的帮助。
interface Person {
name: string;
age: number;
}
interface data {
// how do i write ?
person: Person;
handleShowPerson: () => void ;
}
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];
}
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];
}
you already have the code for person so you just have to annotate your prop with it.你已经有了person的代码,所以你只需要用它来注释你的 prop。 Your handleShowPerson is function and returns JSX as shown below.您的handleShowPerson是 function 并返回 JSX,如下所示。 Lastly you wanted data to be an array so you would have to annotate that too in the interface.最后,您希望数据是一个数组,因此您也必须在界面中对其进行注释。
interface person {
name: string;
age: number;
}
interface data {
person: person;
handleShowPerson: () => JSX.Element;
}
Then you can create an array for your data object by simply initialising然后您可以通过简单的初始化为您的数据 object 创建一个数组
const data: data[] = [person, handleShowPerson];
Arrays can be defined by passing []
after the interface or type. Arrays 可以通过在接口或类型后传递[]
来定义。 So in this example the type becomes:所以在这个例子中,类型变为:
interface person {
name: string;
age: number;
}
interface data {
person: ;
handleShowPerson: ;
}[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.