[英]How to fix the error argument of type boolean or undefined using react and typescript?
i am getting the error我收到错误
"argument of type boolean or undefined isnt assignable to parameter of type boolean. type undefined is not assignable to type boolean" “boolean 类型的参数或未定义的参数不可分配给 boolean 类型的参数。未定义的类型不可分配给布尔类型”
when i am passing prop from child to a usehook like below,当我将道具从孩子传递到下面的使用挂钩时,
below is my code,下面是我的代码,
function Parent() {
const [isDialogOpen, setDialogOpen] = React.useState(false);
return (
<Wrapper>
<DialogComponent isDialogOpen={isDialogOpen} setDailogOpen={setDialogOpen}/>
</Wrapper>
);
}
interface ChildComponentProps {
isDialogOpen: boolean,
setIsDialogOpen: any,
}
function ChildComponent ({isDialogOpen, setIsDialogOpen} : ChildComponentProps) {
const count= 10;
useSomehook(isDialogOpen, count); //error here
return (
<Wrapper>
<div>somedivs</div>
{isDialogOpen && <Overlay/>}
</Wrapper>
);
}
i have useSomehook defined in other file like below,我在其他文件中定义了 useSomehook,如下所示,
export function useSomehook(enabled: boolean, count:number) {
React.useEffect(() => {
if (enabled) {
trigger(count);
}
}, [enabled, count, trigger]);
}
I am new to using typescript.我是使用 typescript 的新手。 i am not sure how to fix this error.
我不知道如何解决这个错误。 could someone help me with this.
有人可以帮我解决这个问题。 thanks.
谢谢。
You have a useState using a boolean.您有一个使用 boolean 的 useState。 In typescript you have to be sure that whatever variable you pass as a boolean in this case can't be undefined.
在 typescript 中,您必须确保在这种情况下作为 boolean 传递的任何变量都不能未定义。
There are multiple solutions, but a quick fix would be to fix you component like this.有多种解决方案,但快速解决方法是像这样修复您的组件。
function ChildComponent ({isDialogOpen, setIsDialogOpen} : ChildComponentProps) {
const count= 10;
useSomehook(isDialogOpen !== undefined ? isDialogOpen : false, count); //error here
return (
<Wrapper>
<div>somedivs</div>
{isDialogOpen && <Overlay/>}
</Wrapper>
);
}
This makes sure that if isDialogOpen is not undefined, we will use that value, otherwise we use the boolean "false".这确保如果 isDialogOpen 不是未定义的,我们将使用该值,否则我们使用 boolean “false”。 You can edit this to your liking of course.
当然,您可以根据自己的喜好对其进行编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.