[英]Typescript complains that react component optional prop could possibly be undefined
I have a simple React component like this:我有一个像这样的简单 React 组件:
interface ComponentProps {
onClick?: () => void;
}
const Component = (props: ComponentProps) => {
if (!props.onClick) {
return <></>;
}
return (
// Typescript complains: Cannot invoke an object which is possibly 'undefined'.ts(2722)
<button onClick={() => props.onClick()}>
test
</button>
);
};
Typescript complains props.onClick could be undefined, even if after the check. Typescript 抱怨 props.onClick 可能未定义,即使在检查之后也是如此。
Could anyone help me to understand why props.onClick can still possibly be undefined?谁能帮我理解为什么 props.onClick仍然可能是未定义的?
This is because you are using the optional property operator ?
这是因为您使用的是可选的属性运算符?
into the ComponentProps
interface definition.进入ComponentProps
接口定义。
I see two ways to solve this issue:我看到有两种方法可以解决这个问题:
The first one is to change the optional property definition to mandatory removing the ?
第一个是将可选属性定义更改为强制删除?
optional property operator, so you don't need to validate if the onClick
function is passed to the component.可选的属性运算符,因此您无需验证onClick
函数是否传递给组件。
interface ComponentProps {
onClick: () => void;
}
const Component = ({onClick}) => (
<button onClick={onClick}>
test
</button>
)
l The second one is to create a handler function in order to validate the optional onClick
function. l 第二个是创建一个处理函数来验证可选的onClick
函数。
inteface ComponentProps {
onClick?: () => void;
}
const Component = ({onClick}: ComponentProps) => (
<button onClick={() => {
if(onClick) onClick();
}}>
test
</button>
)
Bonus.奖金。 You can use spread syntax and ternary operator together to validate optional properties passed to the React component.您可以同时使用扩展语法和三元运算符来验证传递给 React 组件的可选属性。
interface ComponentProps {
onClick?: () => void;
}
const Component = ({onClick}: ComponentProps) => (
<button {...(onClick ? {onClick} : {})}>test</button>
)
The problem is that your props
object is mutable and TypeScript assumes that it can be modified between your !props.onClick
check and the execution of the callback.问题是你的props
对象是可变的,TypeScript 假设它可以在你的!props.onClick
检查和回调执行之间修改。
To fix your issue, you can destructure the props
object and use the onClick
attribute as a scoped variable:要解决您的问题,您可以解构props
对象并将onClick
属性用作范围变量:
const Component = ({onClick}: ComponentProps) => {
if (!onClick) {
return <></>;
}
return (
<button onClick={() => onClick()}>
test
</button>
);
};
Why don't you try你为什么不试试
interface ComponentProps {
onClick?: () => void;
}
const Component = ({ onClick = () => {}}: ComponentProps) => {
return (
<button onClick={() => props.onClick()}>
test
</button>
);
};
use props.onClick?.()
instead of props.onClick()
.使用props.onClick?.()
而不是props.onClick()
。
This tells typescript to call onClick() only if it is defined.这告诉打字稿只有在定义时才调用 onClick() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.