【问题标题】:Enforcing TSX prop type inline for function declaration which declares props using object destructuring对函数声明强制执行 TSX 道具类型内联,该函数声明使用对象解构来声明道具
【发布时间】:2020-08-23 07:29:36
【问题描述】:

我有一个自定义类型

export class MyClass {
  name: string;
  img: string;

  constructor(name: string) {
    this.name = name;
    this.img = `/images/${name}.jpg`;
  }
}

我有一个无状态函数组件,它以该类型为参数

export default (issue: Issue) => {
...
}

当我尝试创建无状态功能组件时

<MagazineCard issue={issues[0] as Issue} />

我得到了错误

Type '{ issue: any; }' is not assignable to type 'IntrinsicAttributes & Issue'.

下面有一个解决方案,但我觉得我应该将此材料留给可能会看到此问题的其他人,以获得替代解决方案和更深入的理解

Object destructuring when initializing the JSX,例如:

<MagazineCard {...issues[0]} />

Create an interface 用于我的无状态功能组件的参数。

注意:types don't need to be specified

属性类型

MagazineCard.propTypes = {
  issue: Issue
}

【问题讨论】:

  • (issue)({issue}) 非常不同。你可以写({issue}: {issue: Issue}),但我怀疑你知道这一点并且正在寻找其他东西。
  • 是的,我在使用 ({issue}) 时遇到了另一个错误,因为我是 typescript 新手,但不确定正确的方法是什么
  • 但这是正确的形式。你不能使用(issue) 这不仅仅是一个 TypeScript 错误,它会在运行时失败

标签: reactjs typescript object-destructuring


【解决方案1】:

这是怎么做的

export default ({issue} : {issue : Issue}) =>  => (
    //...Your JSX component
)

我很困惑,因为它对我来说似乎过于复杂,所以我made a post on reddit asking why this is the syntax for doing it

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2019-07-20
    • 2013-10-12
    相关资源
    最近更新 更多