When destructing a union object flow fails
type Student = {
type: 'student'
};
type Teacher = {
type: 'teacher'
};
const getType1 = (someone : Student | Teacher) => someone.type; // works
const getType2 = ({ type } : Student | Teacher) => type;
// ^ string literal `teacher` [1] is incompatible with string literal `student` [2].
https://flow.org/try/#0C4TwDgpgBAysCuATCA7YUC8UDeAoAkKJAFxQDkAzgsmmbgL665HQAqEAhgMYAWEATphwEWpMsE68BdRri4B7FFSgBzCMFbhoWABTYoLKPSik4SVOgA+Udtz78AlJgB8BrUA
Use generics like this
It has nothing to do with generics and your example fails
It does not "fails". Read the error message. I added the error intentionally to show use that it works.
Here's the version that typechecks.
This was just an example. This error occurs allot when destructing React component's props. Here's another example:
type Message = { type: 'image', data: { url: string } } | { type: 'text', data: { text: string } };
// Doesn't work
const MessageBubble = ({ type, data } : Message) => {
switch (type) {
case 'image': {
return <img src={data.url} />;
}
case 'text': {
return <div>{data.text}</div>;
}
default: {
throw new Error('Unknown message type');
}
}
}
// Works
const MessageBubble2 = (props : Message) => {
switch (props.type) {
case 'image': {
return <img src={props.data.url} />;
}
case 'text': {
return <div>{props.data.text}</div>;
}
default: {
throw new Error('Unknown message type');
}
}
}
https://flow.org/try/#0C4TwDgpgBAshDO8CGBzaBeKBvKpIC4oByASwFtUIiAaKAEyWCUJwFcAnAG0PmHZIB2KKAF9RUAD7Zc4CISLAIAD2A16jZtMUqefQcLEiA3ACgTAYwD2A3lABKEJOeBRMWEWYD0nqABFLCAIKUADuluwA1hbWtnCIlABCrABGyZwYUAAUOHgQtAxM4oRxyGgAlK4AfNgmUFAAkPAhJMDmABZZuRVYtXV95kjw0KQUaEQsvX0N7BDAHAJQADzkwvDs5uhYBUgAdBycYp6VplN1HqdQA0PE2qoTF-Uzc+wLi3QkAG6VWxo7tyKLTzvL4nU7nU50CAAMyQrE4wHup3qwDa7EsISgAggGIAouw0exMkQAKoCCICdELMgIUrQXJEMqgqbgs4mDwmbxQADq4Qi8GiNhcJUSKTSEAATK4smA0WB4FBijTKBV0NUenVGs1Wh1MjLLHK-rJupN+oNhuRKOMag8nvMlisoGsNlg9QbtnsuIdjibWRcrsNblb1UjbS8lsDvq74Dt3f9ARGmX0WX1ITC4QjrUiUWiMVjcfjwkTSeTKVBqfE0DJIAzE76k2ygA
Oh, sorry, it seems like a duplicate of #3918
Am I wrong?
No, it says unions doesn't work well with destructions
I personally can't see any difference between your latest example and an example from #3918
Well, the title of issue is different, but it does not matter.
Could you please clarify the difference?
Because this has nothing to do with refinements
Well, what about #3932 ?
Duplicate of #3932