QuizNot attempted
Class component state field
1–4 to choose, Enter to submit
Show answer & explanation
Correct answer:
- The
statefield 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
statenarrows to{ count: number }(still assignable toReadonly<CounterState>, so no error at the declaration) andlabeldisappears - annotating
state: CounterStatekeeps the full shape. this.propsandsetStatestill 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.