'TS2322: Type 'Atrribute' is not assignable to type 'boolean | undefined'. Toggle

I tried first isToggle and onToggle to be a boolean type, but it still warning about the types after the change you can see below.

This is error of checked: Type 'Atrribute' is not assignable to type 'boolean | undefined'.

This is error of onChange : Type 'Atrribute' is not assignable to type 'ChangeEventHandler'. Type 'Atrribute' provides no match for the signature '(event: ChangeEvent): void'.

import React, {ChangeEventHandler} from "react";
import classNames from "classnames";
import './SwitchToggle.css';

interface Atrribute{
    rounded:boolean;
    isToggled:boolean|undefined;
    onToggle:ChangeEventHandler<HTMLInputElement>;
}

const SwitchToggle =(rounded:Atrribute ,isToggled:Atrribute,onToggle:Atrribute)=>{

    const sliderCX = classNames("slider",{
        "rounded":rounded
    })

    return(
        <label className={"switch"}>
            <input type={"checkbox"} checked={isToggled} onChange={onToggle}/>
            <span className={sliderCX}/>
        </label>
    )
}

export default SwitchToggle;

I also use this code in main and its work fine

const [isToggled,setTisToggled] = useState(false);

<SwitchToggle isToggled{...SwitchToggle.prototype.isToggled} onToggle={()=>setTisToggled(!SwitchToggle.prototype.isToggle)}/>


Solution 1:[1]

I think you should write like this...

const SwitchToggle =({ rounded, isToggled ,onToggle }:Atrribute)=>{

Solution 2:[2]

This isn't how you destructure function arguments:

const SwitchToggle = (rounded:Atrribute ,isToggled:Atrribute,onToggle:Atrribute) => {...}

What you're telling TypeScript here is that this function will receive three arguments, each of them being of type Atrribute. But instead this function will receive one argument, of type Atrribute, from which you want to destructure three properties.

To destructure an object, use the {} destructuring syntax:

const SwitchToggle = ({ rounded, isToggled, onToggle } : Atrribute) => {...}

Solution 3:[3]

Your props declaration is wrong. You can't write your props this way :

const SwitchToggle =(rounded:Atrribute ,isToggled:Atrribute,onToggle:Atrribute) => {...}

Atrribute is the type of your entire props object, so you should write it this way :

const SwitchToggle =(props:Atrribute) => {...}

Or, if you want to destructure your object, then it'll be something like :

const SwitchToggle =({rounded, isToggled, onToggle}:Atrribute) => {...}

P.S. : You misswrote Atrribute.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 grace
Solution 2 David
Solution 3 Quentin Grisel