![](/img/trans.png)
[英]TypeScript conditional types: Extract component props type from react component
[英]TypeScript conditional types for props
我有一个组件可以处于两种不同的状态,编辑模式和查看模式。 为了适应这一点,我有一个联合类型来完成这项工作,但我仍然得到 TypeScript 在我的组件的 args 中抱怨:
type View = {
isEditing: false;
viewHandler: () => void;
someOtherProp: any // this is unique to view mode
};
type Edit = {
isEditing: true;
editHandler: (id: string) => void;
};
export type MyProps = View | Edit;
然后在这里抱怨:
const Item: React.FC<MyProps> = ({
isEditing = false,
editHandler,
~~~~~~~~~~~
}) => {
Property 'editHandler' does not exist on type 'PropsWithChildren<MyProps>'.
我错过了什么?
我认为它也应该出现在您的 View 类型中,如下所示:
type View = {
isEditing: false;
editHandler?:(id: string) => void;
};
type Edit = {
isEditing?: true;
editHandler: (id: string) => void;
};
所以我现在使用的解决方案是添加它并将其输入为never
:
type View = {
isEditing: false;
viewHandler: () => void;
editHandler?: never;
};
type Edit = {
isEditing: true;
editHandler: (id: string) => void;
viewHandler?: never;
};
export type MyProps = View | Edit;
在事件处理程序被调用或传递的地方,我使用!
向 TypeScript 保证这不能未定义。 感谢 Nadia 在上面的评论中为我指明了正确的方向!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.