我在打字和react 方面遇到了问题.
假设我有以下UNION类型:
type Fruits = 'apple' | 'peach' | 'banana';
我是这样使用它的:
type FoodBaseProps = {
fruits: Fruits;
weight: number
price: number
}
现在,假设我有一个名为needToPeel
的布尔props ,它应该只在水果banana
通过时才会被通知;
为了解决这个问题,我做了以下工作:
export type NeedToPeelFruitsProps = FoodBaseProps & {
fruits: Extract<Fruits, 'banana'>;
needToPeel?: boolean;
};
至于其他不需要go 皮的水果,我有:
export type DefaultFruitsProps = FoodBaseProps & {
fruits: Exclude<Fruits, 'banana'>;
};
然后我就有了:
type FoodProps = NeedToPeelFruitsProps | DefaultFruitsProps;
现在,如果我根据这个逻辑做一些断言,我会得到这个(按预期工作):
const testFn = (food: FoodProps) => {
switch (food.fruits) {
case 'banana': {
console.log(food.needToPeel); // No error
break;
}
case 'apple': {
console.log(food.needToPeel); // TS2339: Property 'needToPeel' does not exist on type 'DefaultFruitsProps'.
break;
}
default:
}
};
但是,如果我try 在Reaction组件中访问这个needToPeel
props ,我会遇到一些问题:
const Food = ({
fruits,
weight,
price,
needToPeel, // TS2339: Property 'needToPeel' does not exist on type 'FoodProps'.
}: FoodProps) => {
return (
<FoodBase
fruits={fruits}
weight={weight}
price={price}
needToPeel={needToPeel} // 2 errors below
/>
)
}
1-TS2769: No overload matches this call. Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & [...]
;
2-TS2339: Property 'needToPeel' does not exist on type 'FoodProps'.
我认为问题是因为unions 类型只考虑共同的props .因此,needToPeel
props 将不可访问,因为它不在类型之间共享.
我想知道是否有方法能够访问我的Reaction组件中的needToPeel
.