Thursday, July 20, 2017

TypeScript solves the industry's billion dollar mistake too

Reading about the advantage of Flow over TypeScript. Saw these slides:



With Flow, the error is caught at compile-time instead, which indeeds solves the billion dollar mistake:



TypeScript 2.0 already has the same functionality as Flow, it's just not the default. Just add "strictNullChecks": true to tsconfig.json.



With that settings, possible null/undefined errors can now be caught at compile-time:



If the type is explicitly added to the function it will complain that there is a path that could lead to undefined value:



Just include the undefined value in function's return type:



The inferred return type for function foo if return type is not included is string | undefined

Finally, to fix the undefined error:



Of course, if it can be guaranteed that a function returns a non-null/non-undefined value, no need to add undefined:




Happy Coding!



No comments:

Post a Comment