【问题标题】:Redux state interface: An interface can only extend an object type or intersection of object types with statically known membersRedux 状态接口:接口只能扩展对象类型或对象类型与静态已知成员的交集
【发布时间】:2021-12-15 10:18:16
【问题描述】:

我正在尝试为我的组件道具创建类型定义:

interface ComponentProps<MappedStateProps = AppStateStateProps> extends MappedStateProps, OtherProps {
   // ... some other props here too
}

MappedStateProps 可以是:

  • 完整的应用程序状态(如果没有给出MappedStateProps 类型参数), 或
  • 状态的子集(如果 MappedStateProps 已定义 - 但它并不总是被定义,因此在这种情况下,我们希望假定完整状态 - 又名 AppStateStateProps

我得到的错误是:An interface can only extend an object type or intersection of object types with statically known members.

我该如何解决这个问题?

额外信息:

示例用法:

const a: ComponentProps<{ foo: string }<-- only foo in our state props

const b: ComponentProps  <-- full state in state props

在哪里

type AppStateStateProps = {
    aStr: string;
    aNum: number;
}

【问题讨论】:

  • 请分享可重现的示例。由于MappedStateProps 是计算值(参数),TS 无法确保安全。换句话说,你不能在这个地方使用泛型。 TS 向您显示一条友好的错误消息:只允许具有静态已知属性的类型
  • 您好船长,感谢您的评论。这个例子不能重现吗?
  • 是的,现在可以了。就像我说的,你不能在 TS 期望静态已知类型的地方使用泛型
  • 我明白,我不明白解决方案(解决方法)是什么。
  • ???? ??????它确实有效.. 谢谢请形成答案,以便我可以为您接受。

标签: typescript redux react-redux react-typescript


【解决方案1】:

interface 不允许您扩展具有静态未知成员的对象,但 type 可以。

请使用type 而不是interface

type ComponentProps<MappedStateProps = AppStateStateProps> = MappedStateProps & OtherProps

【讨论】:

    猜你喜欢
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-08-18
    • 2012-01-17
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多