![](/img/trans.png)
[英]React + Typescript: How to define interface for an array that's populated from componentDidMount?
[英]How to define the interface for an array in react and typescript
我有一个名为data
的变量,它是一个包含function
和object
的array
。 我想为此定义一个 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];
}
由于您希望数据成为数组,因此可以执行以下操作:
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];
}
你已经有了person的代码,所以你只需要用它来注释你的 prop。 您的handleShowPerson是 function 并返回 JSX,如下所示。 最后,您希望数据是一个数组,因此您也必须在界面中对其进行注释。
interface person {
name: string;
age: number;
}
interface data {
person: person;
handleShowPerson: () => JSX.Element;
}
然后您可以通过简单的初始化为您的数据 object 创建一个数组
const data: data[] = [person, handleShowPerson];
Arrays 可以通过在接口或类型后传递[]
来定义。 所以在这个例子中,类型变为:
interface person {
name: string;
age: number;
}
interface data {
person: ;
handleShowPerson: ;
}[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.