【问题标题】:TS2339 Property myProperty does not exist on type SetStateAction<User>TS2339 属性 myProperty 在 SetStateAction<User> 类型上不存在
【发布时间】:2021-04-24 05:39:10
【问题描述】:

我正在尝试在 React 中使用 TypeScript,但遇到了一个我不明白的错误:

<html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' does not exist on type '(prevState: User) =&gt; User'.

我正在尝试在我使用useState 设置的对象的方法中使用this,但出现错误:

function fetchUserInfo(
  data: InterfaceJsonUserInfo,
  setUserObject: React.Dispatch<React.SetStateAction<User>>
) {
  setUserObject({
    id: data.id,
    subEnd: new Date(data.subEnd),
    subExpired() {
      const subEndDate = this.subEnd;
      const nowDate = new Date();
      return (subEndDate > nowDate);
    },
  }

这是我的界面:

export interface User {
  id: string, // Uuid
  subEnd: Date,
  subExpired: () => boolean,
}

我不明白为什么会收到错误消息,因为 subEnd 在用户界面上。

当我从&lt;User&gt; 更改为 React.Dispatch&lt;React.SetStateAction&lt;any&gt;&gt; 时,代码确实有效,但我想指定类型而不是使用any。那我做错了什么?

【问题讨论】:

    标签: javascript reactjs typescript object setstate


    【解决方案1】:

    调用subExpired时需要指定thisUser

    export interface User {
      id: string, // Uuid
      subEnd: Date,
      subExpired: (this: User) => boolean,
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2016-03-14
      • 2017-02-25
      • 2021-11-24
      • 2019-01-11
      • 2021-05-08
      • 2021-10-15
      • 2020-12-13
      • 2021-08-04
      相关资源
      最近更新 更多