![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZcZPUGiMrpZbmm4nX697NpC4H6v3AtoJKCb8ZbKrL15BfXxyk_sTFlpK1VCtR0WxalXM4N_uHF_3P4f4d2Acz3YEvVtqgK772ZCIChNIrnqWSSV6ROXH8BW87KHfZKPqHfiN8iFUOobo-/s1600/Screen+Shot+2017-07-20+at+12.26.58+PM.png)
With Flow, the error is caught at compile-time instead, which indeeds solves the billion dollar mistake:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4_UbPMf9i_LiC6aRI0-aFbu4CLhiZBkQSRUsyKoRcL7ZnZrDyjp9AWISxtWnS9nraDoKWQrezekt_U2wT-LMYNIM3-I60YUY5dnh-dkYTlTUsQ6_-Ynrop67RRLHPgpmKv0R3ZdpBLe1z/s1600/Screen+Shot+2017-07-20+at+12.27.25+PM.png)
TypeScript 2.0 already has the same functionality as Flow, it's just not the default. Just add "strictNullChecks": true to tsconfig.json.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8fyNSHqlaQP0k8U3itcjU-LnJ2HS4njcWmKHYhqTHDW93I07-6JRuKSTKI1LaWZ9xSJEnO57TVL9Jj4Bb-VjPNynt4U_DmZW7rb7N_JYcVuIy6UHMfCGlKBEPeowa1RXPfIydFPpxGtB2/s1600/Screen+Shot+2017-07-20+at+12.30.18+PM.png)
With that settings, possible null/undefined errors can now be caught at compile-time:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4q5EMdKV_De9MxXk46HpY3Ki-85IuSQ0BHVKmyW-CXl3vWAQSRgS7jP1QSLdt15-NK_eUrFScUN2yejULw9MWOF8a6FCCKQ-a7fk9uXc5u_0f0o6PW4f1WUQz-RO1PvnV5z_QHgf4VMpC/s1600/Screen+Shot+2017-07-20+at+12.18.59+PM.png)
If the type is explicitly added to the function it will complain that there is a path that could lead to undefined value:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4Qea0rkzAi9c7xcNrEARNaTnUO7hWT-Wyk0p2Dr4EXJqi5UUYQjbmIguWjxmpa6AdEuynRnv91xUYlRG7HVW4My43_426DYeYoqlmQ8Fmnk-q-VDRWulP6vmDCdjSWfxmTJuQFkN4njGr/s1600/Screen+Shot+2017-07-20+at+12.19.55+PM.png)
Just include the undefined value in function's return type:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqCJY9GB88zHD-8JQf5nYFqE6NF0pY5pIXYLwik2KQ-povFph3a1k9f_6jtuiqHp112tQZgEoa8VGrfhOxM2wSWq6b36cec2nNoTaY1a6bDZCNY_LsZMvNRbwcMc-QlTbwaVMecp9wgXB9/s1600/Screen+Shot+2017-07-20+at+12.20.47+PM.png)
The inferred return type for function foo if return type is not included is string | undefined
Finally, to fix the undefined error:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZ5pjL583SzJfp6Dsnmg5HX41iPSqa4XW_kVwrn7Pjz79tfhMfGdwgUDzLxk8JbU4xOa593FLOjtq-SH2Lqzr3aQsPpu942BvBmZ3Qfpfx_qinWyMf5ZlxrJz28utQZT8dQgiWtoIkc4_F/s1600/Screen+Shot+2017-07-20+at+12.22.55+PM.png)
Of course, if it can be guaranteed that a function returns a non-null/non-undefined value, no need to add undefined:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4zXLDSL7jKSFlJTwtn1dpizUbvs8sHMpx2weIyP15ExIwYYR3hw4iXkLpA4pqg3FiUMrT3fqSe5N_I9rbtwUbBIHcsGtxXLC7x_CIVjzFrKJOg06BcJua4Tv4T05STDa7ioBj07oi0pDF/s1600/Screen+Shot+2017-07-20+at+12.25.05+PM.png)
Happy Coding!
No comments:
Post a Comment