How to correctly set initial state in React with Typescript without constructor? How to correctly set initial state in React with Typescript without constructor? reactjs reactjs

How to correctly set initial state in React with Typescript without constructor?


Am I doing it the correct way?

Yes.

Is setting class property directly considered a bad style in Typescript?

No.

A slightly better approach

Consider declaring state as public readonly, and using the Readonly modifier.

This will satisfy TSLint while also giving you some protection against being modified incorrectly (ie. not using this.setState).Even though state is still exposed to the outside, this is never usually a problem.

interface IState {  value: number;}class App extends React.Component<{}, IState> {  public readonly state: Readonly<IState> = {    value: 10  }  public render() {    return <div>{this.state.value}</div>  }}

The TSLint rule

Declaring access modifiers explicitly is a good thing, even if it results in the same access implicitly. It helps keep your code clear, so I wouldn't disable this TSLint rule.


I'd say that setting the state property of a React component directly is poor practice unless you annotate the type to be the same as the state type parameter to React.Component. Without the annotation, TypeScript determines the type of this.state from the initializer, overriding the type from the superclass (which is based on the state type parameter) and won't give you an error if the type from the initializer comes out to be a subtype of the type parameter. This can cause unsoundness or unexpected behavior later; see this thread for an example.


The state is immutable. The recommended way to set the initial state is by the constructor.

Note that 'state' is already defined and inherited so there is no need to re-declare it:

interface AppState {    charge : number;    spin   : number;    color  : string;}interface AppProps {}class App extends React.Component<AppProps, AppState> {    constructor(props) {        super(props);        this.state={ charge: 0, spin: -0.5, color:'red' };     }}

BTW, This is exactly how it is defined in the react documentations:

class Clock extends React.Component {  constructor(props) {    super(props);    this.state = {date: new Date()};  }...