Loudrous
Loudrous

Reputation: 1305

object parameters type definition in typescript

I am passing a component some props. One of this is a function that doesn't return anything. I have to pass two an object as parameter comosed by two booleans. How do I specify that those parameters are booleans?

const MyComponent: React.FC<{
  onChange: ({ isFoo1, isFoo2 }) => void;
}> = ({ onChange }) => {
    const [isFoo1, setIsFoo1] = useState<boolean>(false);
    const [isFoo2, setIsFoo2] = useState<boolean>(false);
  
    /*
    * stuff...
    */

    useEffect({
      onChange({isFoo1, isFoo2})// <----- Type error
    },[isFoo1, isFoo2])
}

The typerror has code 2345 and it appears because on onChange definition I haven't specified the type of the two parameters.. How can I do that?

Upvotes: 1

Views: 1854

Answers (1)

Aplet123
Aplet123

Reputation: 35522

Don't use destructuring in the type of the onChange function. Instead, just use a normal object parameter and type it as you would an object:

onChange: (obj: {isFoo1: boolean, isFoo2: boolean}) => void;

Playground link

Upvotes: 4

Related Questions