[英]Typescript/React - Multiple types for one prop not working
我定义了以下类型。 CurrencyStat
和ScoreStat
扩展了Stat
。
export interface Stat {
value: number;
change?: number;
}
type Currency = "USD" | "RMB";
export interface CurrencyStat extends Stat {
currency: Currency;
}
export interface ScoreStat extends Stat {
outof: number;
}
现在我正在尝试定义一个组件StatDisplay
,以显示统计信息,而不管它是哪种统计类型。 我收到以下错误: Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339)
Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339)
Property 'currency' does not exist on type 'Stat | CurrencyStat'. Property 'currency' does not exist on type 'Stat'.ts(2339)
,即使我在 prop stat
上使用联合类型。
我是这些[reading typescript docs][1]
说“如果我们有一个联合类型的值,我们只能访问联合中所有类型共有的成员。” 这就解释了为什么联合类型在这里可能不起作用,但现在我很难找到一种方法来使它起作用。
我知道可以删除CurrencyStat
并将currency
添加为Stat
的可选属性,但稍后会有更多的统计类型,如果可能的话,我希望将它们分开。
import { CurrencyStat, ScoreStat, Stat } from "../../../../types/types";
export const StatDisplay = ({
label,
stat,
}: {
label: string;
stat: Stat | CurrencyStat;
}) => {
return (
<div className="flex flex-col items-center">
<div className="flex items-center">
<div className="">{stat?.currency}</div>
<div className="text-2xl font-semibold">{stat.value}</div>
</div>
<div className="">{label}</div>
</div>
);
};
CurrencyStat
已经实现了Stat
接口,因为您正在使用它进行扩展。
要解决您的问题,您只需将组件 function params stat
变量更改为CurrenyStat
或Stat & Partial<CurrencyStat>
Partial
意味着您可以使用Stat
键传递 object 但不能保证CurrencyStat
。
这是示例:
export const StatDisplay = ({
label,
stat,
}: {
label: string;
stat: Stat & Partial<CurrencyStat>;
}) => { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.