【问题标题】:How to define the interface for an array in react and typescript如何在反应和打字稿中定义数组的接口
【发布时间】:2022-09-27 23:18:24
【问题描述】:

我有一个名为data 的变量,它是一个array,其中包含一个function 和一个object。我想为此定义一个模型而不是使用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];
}
  • 根据使用情况,这似乎是 tuplepersonhandleShowPerson不是任何事物的属性。
  • 现在你不知道我如何为数据变量定义一个接口吗? @jonrsharpe
  • 为什么要将其定义为接口?你已经有了一个正在运行的接口元组。

标签: reactjs typescript


【解决方案1】:

由于您希望数据成为数组,因此可以执行以下操作:

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

【讨论】:

  • 我们可以将其定义为接口吗?
  • 我认为您不能将Tuple 定义为接口。 type 有什么问题吗?
  • @goodboy 你可以写type _Data = [Person, ✂] 然后interface Data extends _Data {} 但你能解释一下为什么你关心typeinterface 之间的区别吗?好像是 XY 问题
  • 我必须在一个更大的程序中这样写,这只是一个小例子,看看我能做些什么来解决这个问题。你能解决这个问题吗?@jcalz
【解决方案2】:

你已经有了代码所以你只需要用它来注释你的道具。您的处理显示人是函数并返回 JSX,如下所示。最后你想要数据成为一个数组,因此您也必须在界面中对其进行注释。

interface person {
    name: string;
    age: number;
}
interface data {
    person: person;
    handleShowPerson: () => JSX.Element;
}

然后你可以通过简单的初始化为你的数据对象创建一个数组

const data: data[] = [{person, handleShowPerson}];

编辑

我想我误解了你的问题。上面的答案是,如果你想要一个包含多个 person 元组和函数的数组。如果您只想拥有一个具有任何这两件事的数量,但它们没有耦合在一起,您可以将其键入为:

type Data = Person | ((person: Person) => JSX.Element);

然后像这样输入你的变量:

const data: Data[] = [person, handleShowPerson];

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 2017-01-21
  • 2021-03-22
  • 2020-01-13
  • 2020-11-18
  • 2016-08-29
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多