|
|
|
|
|
by yladiz
3148 days ago
|
|
So Flow seem to be complaining that number and string are incompatible types for the array elements. I attempted to change your arr.push(3) statement to one that is appending a string, and it gave the same error even though it should not have given an error in that case. Neither Flow nor TypeScript are correct in this instance. Neither keep track of the actual array element's value, just the general type of the array, which means they actually don't know for sure and do their best guess. So in the Flow example, it complains that the number and string types are incompatible even though it doesn't know that this specific case is incompatible, just the general case. In the TypeScript example, it should keep track of the type of the argument value supplied during the function invocation, not the type for the argument declaration. In this case I would argue that even though TypeScript is incorrect, it's preferable to Flow because Flow doesn't infer that the types are incompatible from actual usage but theoretical. |
|
This example is quite interesting because javascript itself does not provide a way to check the type of an array, unlike a primitive. This is likely due to the fact that an empty array doesn't really have a type for it's items yet.
Here is an example where typescript can infer the type using the `typeof` runtime check but provide compile time checking.
https://www.typescriptlang.org/play/index.html#src=function%...