react props中union和intersection类型的问题


type LinkProps =  {
children: any:
....(some more common props)
};
type LinkWithToProps = LinkProps & {
to: string | { pathname: string };
};
type LinkWithOnclickProps = LinkProps & {
onClick: (params: any) => void;
};
type propsType = LinkWithOnclickProps | LinkWithToProps
const InternalLink = (props: propsType) => {
const {to, onClick, children} = props;
}

我试图使用联合和交集的概念在这里的道具在react组件。我想做的是我的组件可以有一个"to"道具或"onclick";如果两者都不存在,typescript就会报错。

就我的理解而言,我将linkPropsLinkWithToPropsLinkWithOnclickProps结合起来,然后使用|,因此一次只使用其中一个。

但是typescript抱怨Property 'to' does not exist on type 'propsType'.onlCick也是一样的。我不知道我哪里做错了

TS联合是这样工作的。

我相信只有一种安全的解决方案。您应该向这两种类型添加所需的属性。这里有一个例子:

import React from 'react';
type LinkProps = {
children: any;
};
type LinkWithToProps = LinkProps & {
to: string | { pathname: string };
} & { type: 'with' }
type LinkWithOnclickProps = LinkProps & {
onClick: (params: any) => void;
} & { type: 'without' };
type Props = LinkWithOnclickProps | LinkWithToProps
const InternalLink: React.VFC<Props> = (props: Props) => {
if (props.type === 'with') {
const p = props; // LinkWithToProps
}
if (props.type === 'without') {
const p = props; // LinkWithOnclickProps
}
return null
}

你也可以使用typeguard

在这里你可以找到更多的例子

在您的情况下:const {to, onClick, children} = props;TS无法确定哪个属性存在,哪个不存在。在这种特殊情况下,TS只能100%确定children属性。

你应该帮助TS治疗病情

最新更新