Skip to content

QuizNot attempted

Class component state field

Why does this.state.label error here even though CounterState declares label?
type CounterState = { count: number; label?: string };
class Counter extends Component<CounterProps, CounterState> {
state = { count: 0 };
render() { return <p>{this.state.label}</p>; }
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • The state field is typed from its initializer ({ count: number }), which redeclares the inherited type; annotate it: state: CounterState = { count: 0 }
  • A class field without an annotation gets the type of its initializer, not the base class's, so state narrows to { count: number } (still assignable to Readonly<CounterState>, so no error at the declaration) and label disappears
  • annotating state: CounterState keeps the full shape.
  • this.props and setState still use the generics.
  • Not 'generics are swapped': the order is Component<Props, State>.
  • Not 'optional fields not allowed': they are fine.
  • Not 'must be set in the constructor': a class field is the idiomatic way
  • it just needs the annotation.