Vlives
Vlives

Reputation: 415

Typescript and React setting initial state with empty typed array

Say I have the following snippet:

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

Since I am trying to set alarms: [] Typescript doesn't like it, as [] != Alarm[]. I found that I can use alarms: new Array<Alarm>() which initializes an empty typed array, however I don't really like this syntax - is there an easier/better approach?

Upvotes: 28

Views: 40001

Answers (3)

rahulnikhare
rahulnikhare

Reputation: 1486

Declaration:

alarms: Array<Alarm>

Initialization in state :

this.setState({
var1:'',
var2:''
});

I prefer the above declaration

Upvotes: -2

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

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<State> = {
        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.

Upvotes: 46

Air1
Air1

Reputation: 567

Would

alarms: [] as Alarm[]

work for Typescript and for you ?

See this question on how you can cast arrays in Typescript : TypeScript casting arrays

Upvotes: 26

Related Questions