In modern JS, we can directly set an initial state for a React component like this:
class App extends React.Component {
state = {value: 10}
render() {
return <div>{this.state.value}</div>
}
}
When I am trying to do this with Typescript, TSLint says "The class property 'state' must be marked either 'private', 'public', or 'protected'". If I set it to "private", the linter will report Class 'App' incorrectly extends base class 'Component<{}, { value: number; }, any>'. Property 'state' is private in type 'App' but not in type 'Component<{}, { value: number; }, any>'. on App. I am aware that I can tweak the linter rules to skip this kind of checks, but checking the visibility of class properties in general is a good thing I want to utilize.
After testing out all three options, only choosing "public" won't get TSLint throw out errors. But since the state here represents the internal state of this specific component, setting it to public seems pretty weird. Am I doing it the correct way?
class App extends React.Component<{}, { value: number }> {
public state = { value: 10 };
public render() {
return <div>{this.state.value}</div>;
}
}
In all TS-React tutorials I've found online, a constructor is used, like in the old JS syntax.
class App extends React.Component<{}, { value: number }> {
constructor(props: any) {
super(props);
this.state = { value: 10 };
}
public render() {
return <div>{this.state.value}</div>;
}
}
Is setting class property directly considered a bad practice/style in Typescript?
public, it would automatically be public. You can useprivateif you want since you won't be using the state outside of the class anyway, but ultimately it doesn't matter much.private, TSlint will reportClass 'App' incorrectly extends base class 'Component<{}, { value: number; }, any>'. Property 'state' is private in type 'App' but not in type 'Component<{}, { value: number; }, any>'.onApp. I am aware that I can configure TSlint to hide this kind of checks, but checking the visibility of class properties in general is a good thing I want to utilize.publicis redundant.stateshouldn't be private.publicinComponentand that's that. It's not something to worry about.