React + TypeScript 错误整理 Property ‘count’ does not exist on type ‘Readonly<{}>‘.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import * as React from 'react'

interface IProps {
  name: string,
  age: number,
}
export default class Hello extends React.Component<IProps> {
  public constructor(props: IProps) {
    super(props)
    this.state = {
      count: 1
    }
  }
  public render() {
    const { name, age} = this.props
    return (
      <div>
        <h1>Hello .tsx name: {name} age: {age}</h1>
        <h2>{this.state.count}</h2>
      </div>
    )
  }
}

报错信息:
Property 'count' does not exist on type 'Readonly<{}>'.

修改后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import * as React from 'react'

interface IProps {
  name: string,
  age: number,
}
interface IState {
  count: number
}

export default class Hello extends React.Component<IProps, IState> {
  public constructor(props: IProps) {
    super(props)
    this.state = {
      count: 1
    }
  }
  public render() {
    const { name, age} = this.props
    return (
      <div>
        <h1>Hello .tsx name: {name} age: {age}</h1>
        <h2>{this.state.count}</h2>
      </div>
    )
  }
}