首页 > 解决方案 > 用于道具的 TypeScript 条件类型

问题描述

我有一个组件可以处于两种不同的状态,编辑模式和查看模式。为了适应这一点,我有一个联合类型来完成这项工作,但我仍然让 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>'.

我错过了什么?

标签: reactjstypescriptreact-typescript

解决方案


所以我现在使用的解决方案是添加它并将其输入为never

type View = {
    isEditing: false;
    viewHandler: () => void;
    editHandler?: never;
};

type Edit = {
    isEditing: true;
    editHandler: (id: string) => void;
    viewHandler?: never;
};

export type MyProps = View | Edit;

在事件处理程序被调用或传递的地方,我使用 a!来向 TypeScript 保证这不能是未定义的。感谢 Nadia 在上面的评论中为我指明了正确的方向!


推荐阅读