Festina
Festina

Reputation: 325

how to write type in typescript correctly

I can not understand how to solve a problem. I have a default state, where randomActivity is underlined by red and console shows a mistake.

const defaultState: MainState = {
   randomActivity: [],
};

The mistake:

 Type 'never[]' is missing the following properties from type 'Activity': type, key, participantsts(2739)
mainTypes.tsx(13, 3): The expected type comes from property 'randomActivity' which is declared here on type 'MainState'
(property) MainState.randomActivity: Activity

its interface

export interface Activity {
  activity: string;
  type: string;
  key: number;
  participants: number;
}

export interface MainState {
  randomActivity: Activity;
}

interface of action

interface GetActivity {
  type: ActionTypes.GET_ACTIVITY;
  payload: Activity;
}

In the randomActivity is emty. Data from api-request is written into it after clicking on the button. The I get data, write it to the object randomActivity and use in the modal window.

Upvotes: 0

Views: 30

Answers (1)

vijayst
vijayst

Reputation: 21904

Since randomActivity is of type Activity, set its default to null

const defaultState: MainState = {
   randomActivity: null,
};

Or ignore setting a default state.

You may also want to set randomActivity as optional.

export interface MainState {
  randomActivity?: Activity | null;
}

Upvotes: 1

Related Questions