I'm not sure something like this exists, but it would be great to steal this feature from Typescript
In typescript you can define functions whose return types can be annotated as follows:
function isArray(value: any): value as Array<any> {
return _.isArray(value)
}
This makes it easy to write code that gives hints to the type system. Plus, when supporting old browsers, or using a library like lodash, flow only understands that the function returns a boolean.
Soon.
I believe the TypeScript syntax isX is Y. Noting this here as I was looking to create the same issue.
Working on a project just now I also realised that some sort of syntax like the following could also be quite useful:
function testNonNull<T>(val: ?T) : noreturn when val == null {
if (val == null) {
throw new Error("Null");
}
}
The idea being that when writing tests one can annotate the assert methods as throwing in case something doesn't work and then the types will flow as intended. I don't care much for the actual syntax chosen, but if somehow it would be possible to get this to work, I'd be quite happy :). Obviously with functions written in flow having this kind of interprocedural analysis built in would be quite amazing, but being able to annotate it such that it would work in declaration files is essential :)
I'm not exactly sure what you mean here. I think you can achieve whatever you're trying to with function overloads.
What flow doesn't support is a special type for functions that throw. Maybe a throws keyword a la Swift is a good idea?
Here's a bit more elaborate example.
Given this function and declaration:
function assertNotNull<T>(val: ?T) {
if (val == null) {
throw new Error("null value");
}
}
declare function getMaybeString() : ?string;
I would like to some how annotate assertNotNull as not returning (throwing or process.exit) when val is null or undefined. Thus allowing me to write:
const s = getMaybeString();
assertNotNull(s)
const l = s.length;
That is - after the call to assertNotNull flow knows that s is string.
The team is working on a feature that will cover this usecase. Stay tuned.
Is this boolean %checks syntax?
Most helpful comment
The team is working on a feature that will cover this usecase. Stay tuned.