简体   繁体   English

类型反应打字稿上不存在属性

[英]Property does not exist on type react typescript

I'm a newbie in typescript, could anyone please tell me why do I get this error?我是打字稿的新手,谁能告诉我为什么会出现这个错误?

Property 'interval' does not exist on type 'App'. “应用程序”类型上不存在属性“间隔”。

interface State {
  userInput:string[];
  secondsPassed:number;
  }


class App extends React.Component<any, State>{
    state:State = {
      userInput:[],
      secondsPassed:0
    }
  startTimer = () => {
      this.interval = setInterval( () => {
        this.setState(() =>{
          return {secondsPassed: this.state.secondsPassed+1}
        })
      },1000)
    
  }

Try something like this:尝试这样的事情:

 const interval = setInterval(() => {
    this.setState(() =>{
          return {secondsPassed: this.state.secondsPassed+1}
        })
      },1000)

Typescript is a statically-typed language. Typescript 是一种静态类型语言。 Part of that means you have to declare the variables of a class before its assignment.这部分意味着您必须在赋值之前声明类的变量。 Simply declare interval as in the following:简单地声明interval如下:

class App extends React.Component<any, State>{
  interval

  state:State = {
    userInput:[],
    secondsPassed:0
  }
  startTimer = () => {
    this.interval = setInterval( () => {
      this.setState(() =>{
        return {secondsPassed: this.state.secondsPassed+1}
      })
    },1000)

  }

The first answer got it close, the solution looks like this:第一个答案很接近,解决方案如下所示:

 class App extends React.Component<any, State>{
      private interval: any ;
        state:State = {
          userInput:[],
          secondsPassed:0
        }
      startTimer = () => {
          this.interval = setInterval( () => {
            this.setState(() =>{
              return {secondsPassed: this.state.secondsPassed+1}
            })
          },1000)
        
      }

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

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