[英]TypeScript conditional types for props
I have a component that can be in two different states, editing mode and viewing mode.我有一个组件可以处于两种不同的状态,编辑模式和查看模式。 To accommodate for that I have a union type to make this work, but I still get TypeScript complaining in the args of my component:
为了适应这一点,我有一个联合类型来完成这项工作,但我仍然得到 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;
It is then complaining here:然后在这里抱怨:
const Item: React.FC<MyProps> = ({
isEditing = false,
editHandler,
~~~~~~~~~~~
}) => {
Property 'editHandler' does not exist on type 'PropsWithChildren<MyProps>'.
What am I missing?我错过了什么?
I think it should also be present in your View type like this:我认为它也应该出现在您的 View 类型中,如下所示:
type View = {
isEditing: false;
editHandler?:(id: string) => void;
};
type Edit = {
isEditing?: true;
editHandler: (id: string) => void;
};
So the solution I used now is adding it and typing it as never
:所以我现在使用的解决方案是添加它并将其输入为
never
:
type View = {
isEditing: false;
viewHandler: () => void;
editHandler?: never;
};
type Edit = {
isEditing: true;
editHandler: (id: string) => void;
viewHandler?: never;
};
export type MyProps = View | Edit;
And at the point where the event handler gets invoked or passed down, I use a !
在事件处理程序被调用或传递的地方,我使用
!
to assure TypeScript that this cannot be undefined.向 TypeScript 保证这不能未定义。 Kudos to Nadia who pointed me in the right direction in a comment above!
感谢 Nadia 在上面的评论中为我指明了正确的方向!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.