'Why doesn't typescript warn about the return type in this function?
For example, I have an onClick handler on a <div> tag. The handler should expect a return type of React.MouseEventHandler<HTMLDivElement> | undefined . But, I still can return a boolean value of false when temp = false. Got confused here why Typescript did not warn me about the return type
import React from 'react';
const Dummy= () => {
const [temp, settemp] = React.useState(false)
const [text, settext] = React.useState('Hi')
const handler : React.MouseEventHandler<HTMLDivElement> | undefined = () =>{
return temp && settext('bye')
//return temp
}
return (
<div onClick={handler}> Testing </div>
);
};
export default Dummy;
Solution 1:[1]
You're telling typescript that the handler variable is React.MouseEventHandler<HTMLDivElement> | undefined. Note that it is never actually undefined, as it is a const and is therefore only ever a function. You're not telling it what the function's return type is. These are two different things. The return type is either derived from what you return in the function, or you can explicitly declare it after the parameters, like this:
let sum = (x: number, y: number): number => {
return x + y;
}
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 | Luke Briggs |
