typescript-vs-flowtype
typescript-vs-flowtype copied to clipboard
docs: add %checks and T is x
Hi @Bjeaurn. This feature is not unique to Flow, as TypeScript has an equivalent (and even more advanced/useful): T is SomeType
return type.
I'd happily accept a description/comparison of both features into the readme.
(and even more advanced/useful)
This kind of comments make this project lose all its credibility, just FYI
Is the comment inaccurate? If so, you could elaborate
They do the same thing
They don't do the same thing @FezVrasta. You can't use %checks
in declarations in all the cases where you can use x is T
, making its usefulness limited.
Below is one really useful example taken from the TypeScript's library definition (Array.filter
):
interface Array<T> {
filter<S extends T>(callbackfn: (value: T, index: number) => value is S): S[];
}
This makes is possible refine the type of an Array by filtering it.
You can't model this with %checks
(or with Flow altogether). If you could, Flow's official library would do it (it doesn't).
Additionally, %checks
doesn't work in class methods.
I apologize for not being clear in my first comment, but my intention is completeness, not bias against any of the two technologies.
How can you say the Array#filter
TypeScript's type definition is correct? It expects the callbackFn to return a type extended from T
while it should accept any value and cast it to boolean
🤔
The Flow definition seems way more accurate, since it allows to return any
from the callback.
That's not the meaning of value is T
. The return value still has to be a boolean (just like with %checks
).
The difference is in the fact that such defined boolean
has extra meaning attached to it, in that it ensures the mapping between: true
and value is T
, versus in the case of Flow, it ensures the value is "checked" against the logic within the body of the function.
Here's an example comparing the two in respective playgrounds: TypeScript vs Flow
All in all, %checks
is similar to TypeScript's param is T
, with these exceptions:
-
%checks
cannot appear in class methods (that's why it cannot be defined in theArray
case) - you cannot mark a check with an arbitrary type in Flow - it only works based on the logic defined in the body of the function: i.e. things like
typeof
,instanceof
will work, but not complex cases where you reuse logic from a different function, or in cases where there is no body at all (e.g. library definitions))
The two reasons above make TypeScript's param is T
more powerful and useful.