Typescript and React setting initial state with empty typed array

前端 未结 3 1678
醉梦人生
醉梦人生 2021-02-12 16:00

Say I have the following snippet:

interface State {
  alarms: Alarm[];
}
export default class Alarms extends React.Component<{}, State> {
  state = {
    a         


        
3条回答
  •  忘了有多久
    2021-02-12 16:13

    The problem is that when you create a field in a class the compiler will type that field accordingly (either using the explicit type or an inferred type from the initialization expression such as in your case).

    If you want to redeclare the field, you should specify the type explicitly :

    export default class Alarms extends React.Component<{}, State> {
        state: Readonly = {
            alarms: []
        };
    }
    

    Or set the state in the constructor:

    export default class Alarms extends React.Component<{}, State> {
        constructor(p: {}) {
            super(p);
            this.state = {
                alarms: []
            };
        }
    }
    

    You could also cast the array to the expected type, but if there are a lot of fields it would be better to let the compiler check the object literal for you.

提交回复
热议问题