I have a boolean in an Interface. I use it to change some CSS for a sidebar.
I want a button to change the state of the prop sidebarOpen
Here is my attempt :
interface ISidebar {
logout?: boolean;
sidebarOpen?: boolean;
}
class Sidebar extends Component<ISidebar> {
render() {
const handleSidebar = () => {
this.props.sidebarOpen ? this.props.sidebarOpen(false) : this.props.sidebarOpen(true);
};
return (
[...]
<button onClick={handleSidebar} className="buttonSideBar">-</button>
[...]
This handleSidebar
method does not work. I have a typescript error : Type 'Boolean' has no call signatures.
Any idea how I can make this work ?
CodePudding user response:
Your interface signature (more specifically the sidebarOpen? boolean;
part) says that the sidebarOpen
prop is an optional boolean value (i.e. it is either true
, false
, or undefined
).
A boolean value is not a function.
Then in your const handleSidebar
function, you try to call this.props.sidebarOpen
as a function, with a boolean value.
More specifically, you try to use it as both a boolean value and a function.
You use it as a boolean value when you do the this.props.sidebarOpen ? ... : ...
statement. Then, within each of those branches, you try to call the same prop as a function. If that prop is a boolean value, it cannot be called as a function.
My guess is that you need some additional prop that is a function that will open the sidebar.
It might look something like this:
interface ISidebar {
logout?: boolean;
sidebarOpen?: boolean;
openSidebar: (a: boolean) => void;
}
...and then later in the code:
this.props.sidebarOpen ? this.props.openSidebar(false) : this.props.openSidebar(true);
I do not know the specifics of your particular program, but I know that you cannot use the same prop as both a boolean value for checking state and a function at the same time.