Comment by ricardobeat
6 years ago
In this case not even TypeScript can rescue you. You might naively implement:
const head = (input: A[]) => input[0]
and it will happily infer a return type of A. Then you'll fall flat on your face the first time you encounter an empty array:
head([]) // -> undefined
To make it correct you need to explicitly define a return type of (input: A[]): A | undefined, just as the Maybe. It's obviously impossible for TS to guarantee that an array will not be empty at runtime, but I wish this specific case triggered some help from the type checker.
> It's obviously impossible for TS to guarantee that an array will not be empty at runtime, but I wish this specific case triggered some help from the type checker.
http://www.typescriptlang.org/play/#code/C4TwDgpgBAcg9gOwKIF...
It's impossible for Haskell to guarantee an array will not be empty at runtime as well; that's why we can write a new type + a smart constructor to track runtime properties.
A possibly more elegant TypeScript solution:
https://www.typescriptlang.org/play/?ssl=5&ssc=2&pln=1&pc=1#...
> It's obviously impossible for TS to guarantee that an array will not be empty at runtime,
Maybe you could use "Rest elements in tuple types" and do an overloaded signature like this:
(not tested)
You'd have to spread the arguments or use call/bind/apply, though.
[1]: https://github.com/microsoft/TypeScript/pull/24897