Home > Software design >  is it possible to give an empty object in react state for the init default value
is it possible to give an empty object in react state for the init default value

Time:04-18

I am using react "react": "^17.0.0" to build an app using typescript, define the app state like this:

export interface IRoleState {
    data: API.RoleItem,
    menus: API.MenuItem,
}

when I define the state:

const RoleModel: IRoleModel = {
    namespace: 'roles',
    state: {
        data: {
            id: 1,
            name: ''
        },
        menus: {}
    }
}

the IDE told that warning:

Type '{}' is missing the following properties from type 'MenuItem': id, name, children

what should I do to give the init state of the menu? I just want to give the empty object because I still did not know the init value of the menu. should I must write it like this?

const RoleModel: IRoleModel = {
    namespace: 'roles',
    state: {
        data: {
            id: 0,
            name: ''
        },
        menus: {
            id: 0,
            name: 'default',
            children: []
        }
    },
}

CodePudding user response:

If you absolutely must insert a non-conforming value for state.menus, you can force TS to believe it's the right thing:

const RoleModel: IRoleModel = {
    namespace: 'roles',
    state: {
        data: {
            id: 1,
            name: ''
        },
        menus: {} as API.MenuItem // casts empty object as expected type
    }
}
  • Related