简体   繁体   English

TS2339 属性 myProperty 在 SetStateAction 类型上不存在<user></user>

[英]TS2339 Property myProperty does not exist on type SetStateAction<User>

I'm trying to use TypeScript in React and getting an error I don't understand:我正在尝试在 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'.

I'm trying to use this in a method for an object I am setting with useState , and am getting an error:我正在尝试在 object 的方法中使用this ,我正在使用useState进行设置,但出现错误:

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);
    },
  }

And here's my interface:这是我的界面:

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

I don't understand why I'm getting the error because subEnd is on the User interface.我不明白为什么我会收到错误,因为subEnd在用户界面上。

When I change from <User> to React.Dispatch<React.SetStateAction<any>> , the code actually works, but I want to specify the type instead of using any .当我从<User>更改为React.Dispatch<React.SetStateAction<any>>时,代码实际上可以工作,但我想指定类型而不是使用any So what am I doing wrong?那么我做错了什么?

You need to specify that the this is a User when calling subExpired :您需要在调用subExpired时指定thisUser

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM