[英]Why doesn't typescript warn about the return type in this function?
For example, I have an onClick handler on a <div>
tag.例如,我在
<div>
标记上有一个 onClick 处理程序。 The handler should expect a return type of React.MouseEventHandler<HTMLDivElement> | undefined
处理程序应该期望返回类型为
React.MouseEventHandler<HTMLDivElement> | undefined
React.MouseEventHandler<HTMLDivElement> | undefined
. React.MouseEventHandler<HTMLDivElement> | undefined
。 But, I still can return a boolean value of false when temp = false
.但是,当
temp = false
时,我仍然可以返回 false 的 boolean 值。 Got confused here why Typescript did not warn me about the return type在这里感到困惑为什么 Typescript 没有警告我有关返回类型的信息
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;
You're telling typescript that the handler
variable is React.MouseEventHandler<HTMLDivElement> | undefined
您告诉 typescript
handler
变量是React.MouseEventHandler<HTMLDivElement> | undefined
React.MouseEventHandler<HTMLDivElement> | undefined
. 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.请注意,它实际上从来都不是未定义的,因为它是一个常量,因此永远只是一个 function。您没有告诉它函数的返回类型是什么。 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:
返回类型要么派生自您在 function 中返回的内容,要么您可以在参数之后显式声明它,如下所示:
let sum = (x: number, y: number): number => {
return x + y;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.