React组件Props中使用Flow disjoint unions报错求助
Let's break down what's happening here and why you're seeing that error.
The Root Cause
Your Props type uses a disjoint union tied to boolean literals (true/false) for isEditable, which creates a strict link between isEditable's value and uploadUrl's type. However, when you pass a variable typed as bool (like const isEditable: bool = true;), Flow treats that variable as a general boolean type—not a specific literal value.
Flow can't guarantee at compile time that the bool variable will always be exactly true or exactly false (even if you initialize it with a literal, the type remains bool). Since your Props union requires isEditable to be one of the two literal values, Flow can't match the general bool type to either branch of your union, hence the error.
Fixes to Try
1. Pass Literal Values Directly
Instead of using a variable, pass true or false directly in the component props. This lets Flow immediately match the correct union branch:
// Works for editable state <Something isEditable={true} uploadUrl="https://your-upload-url.com" imageUrl="img.jpg" username="johndoe" /> // Works for non-editable state <Something isEditable={false} uploadUrl={null} imageUrl="img.jpg" username="johndoe" />
2. Narrow the Variable's Type with Conditionals
If you need to use a variable, add conditional checks to narrow its type. Flow will infer the literal value in each branch:
const isEditable: bool = true; if (isEditable) { <Something isEditable={isEditable} uploadUrl="https://your-upload-url.com" imageUrl="img.jpg" username="johndoe" /> } else { <Something isEditable={isEditable} uploadUrl={null} imageUrl="img.jpg" username="johndoe" /> }
In each conditional block, Flow knows exactly whether isEditable is true or false, so it can safely match the corresponding union type.
3. Use Type Assertions (Carefully)
You can force Flow to treat the variable as a literal type with a type assertion. Note that this bypasses Flow's type checking, so only use it if you're 100% sure the variable's value matches the assertion:
const isEditable: bool = true; <Something isEditable={isEditable as true} uploadUrl="https://your-upload-url.com" imageUrl="img.jpg" username="johndoe" />
Why Your Original Type Setup is Correct (But Needs Context)
Your disjoint union definition is actually the right approach for linking isEditable and uploadUrl—it enforces the exact relationship you want. The issue is just how Flow handles general boolean variables vs. literal boolean values in union type matching.
内容的提问来源于stack exchange,提问作者kr1x

