0

I have a react component PageLayout written in typescript:

export interface IPageLayoutProps {...}
export interface IPageLayoutActions {...}
export interface IPageLayoutLocalState {...}

export default
class PageLayout<P extends IPageLayoutProps & IPageLayoutActions, S extends Object>
extends React.Component<P, S>
{
    render() {
        return (...)
    }
}

and then I try to extend this component like this:

import PageLayout, { IPageLayoutProps, IPageLayoutActions, IPageLayoutLocalState } from './PageLayout'

export interface IPageLayoutSidebarProps {...}
export interface IPageLayoutSidebarActions {...}
interface IPageLayoutSidebarState {sidebarVisible: boolean}

export default
class PageLayoutSidebar<P extends IPageLayoutSidebarProps & IPageLayoutSidebarActions & IPageLayoutProps & IPageLayoutActions, S extends IPageLayoutSidebarState & IPageLayoutLocalState>
extends PageLayout<P, S>
{
    render() {
       return (...)
    }

    toggleSidebar(visible:boolean) {
        this.setState({
            ...this.state,
            sidebarVisible: visible
        })
    }
}

the problem is that I'm getting error when trying to call this.setState, it tell me that "spread types may only be created from object types". Anyone has any idea what could be wrong with state and why I can't use spread operator on it?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Lukas Kral
  • 987
  • 13
  • 22

1 Answers1

0

Try to use just:

this.setState({sidebarVisible: visible})
Vitalii Andrusishyn
  • 3,984
  • 1
  • 25
  • 31
  • 1
    Should be `this.setState({ sidebarVisible: visible })` – Nitzan Tomer Feb 01 '17 at 15:37
  • seems not to work for me. If I do that, I got "Argument of type '{ sidebarVisible: boolean }' is not assignable to parameter of type S". But if I assign whole state to a variable first, then change key on that variable and pass that variable to setState, it works. – Lukas Kral Feb 01 '17 at 16:03
  • which version of the react types do you use? I don't know when this feature was added, but with "@types/react": "15.0.6" you can use the setState method with a subset of the state – Kalle Feb 01 '17 at 20:06
  • That was the problem, I was using some ancient version of @types/react – Lukas Kral Feb 02 '17 at 08:25