【发布时间】:2021-04-19 22:19:42
【问题描述】:
我有一个自定义的Factory 类型,可以让我创建工厂函数。
export type Factory<T> = (state?: Partial<T>) => T;
我有一个<Avatar /> React 组件,它有一个联合类型作为道具,因为它可以有两个版本(只是图像,或可点击的图像)。换句话说,组件可以有一个或两个属性。
type AvatarOnlyProps = {
alt: string;
src: string;
};
type ClickableAvatarProps = {
alt: string;
label: string;
onClick:
| ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
| undefined;
src: string;
};
export type AvatarProps = AvatarOnlyProps | ClickableAvatarProps;
我想为头像的道具创建一个工厂函数。我试着这样输入:
const createProps: Factory<AvatarProps> = ({
alt = 'Your avatar',
label,
onClick,
src: source = '/images/default-avatar.png',
} = {}) => ({ alt, label, onClick, src: source });
但是 TypeScript 抱怨:
Property 'label' does not exist on type 'Partial<AvatarOnlyProps> | Partial<ClickableAvatarProps>'.
在工厂函数的参数中。
我怎样才能使错误消失?我怎样才能让 TypeScript 理解,在这个工厂函数中,onClick 和 label 都将被提供,或者都不提供?
【问题讨论】:
-
label在AvatarOnlyProps上不存在,因此尝试解构参数会导致编译器投诉。在尝试访问针对这些类型定义的属性之前,您需要使用 type guards 解析输入参数类型。
标签: typescript typescript-typings factory union-types typescript-types