Union Types as variable doesn't work
I have some error with the Union Types, Did I do something wrong?
Union Types doesn't work if I defined variable and pass it to function.
https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgAKA8gMoAqAQnACZZgC8YAggE6sCGWAPAHYCuAWwBGeVmAA+YAM4ZWAS14BzAHzoAxnF6ywUfr3UZ5W8nh1MAFDg6dB0gFxEyVWlgCUjFWADeqMP7BNbTgYPAA6eCUrGw47N1QAX3RUIJ0bTiwAOSFRVkc2DL4csS8mAG0ARgAaMAAmGoBmGoAWAF0UrTT2LlI5RSV87p5ZBWVSsDKAcgrJmsna2bBJhsXJ5sn21D0DIxMzDAt0rmyRMXjtw2NeU1lDod7RpTcgA
Array<number> | Array<string> is different than Array<number | string> because [1, 'foo'] is valid for the second one but not for the first.
/* @flow */
type POSTBody = Array<number> | Array<string>
const functionTest = (params: POSTBody) => {
console.log(params)
}
const arrayNumber: Array<number> = [1, 2, 3, 4]
const arrayString: Array<string> = ['1', '2', '3', '4']
functionTest(arrayNumber)
functionTest(arrayString)
If you want to give an array that can contain numbers and/or strings, it only works if you won't mutate it in your function, and tell so by using read-only array:
/* @flow */
type POSTBody = $ReadOnlyArray<number | string>
const functionTest = (params: POSTBody) => {
console.log(params)
}
const arrayNumber: Array<number> = [1, 2, 3, 4]
const arrayString: Array<string> = ['1', '2', '3', '4']
functionTest(arrayNumber) // OK
functionTest(arrayString) // OK
https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgAKA8gMoAqAQnACZZgC8YAJAEp4CGNxAdjFgEEATkI5YAPDwCuAWwBGeIWAA+YAM4YhASx4BzAHzoAxnB4awUKTyMYtp8nnNMAFDg6iZagFxEyVWlgAlIz6YADeqGBRYCZmcDB4AHTwuq7uHJ6BqAC+6Kix5u6iWABysgpCPsLFkuWKoUwA2gCMADRgAEztAMztACwAuvmmhSJipJo6ulVjEhraeg1gjQDkzSvtKx0bYCvdOyt9K0Oolta29o4YzkViZfKKWWc2djwOGjezEwu6gUA
Feel free to re-open if you feel like your question wasn't answered.