Hacker News new | past | comments | ask | show | jobs | submit login

> it’s important to remember that TypeScript does not provide any assurances about a variable’s runtime type, especially if the data is coming from an external source (like an API). In those cases, you often need to use type assertions or guards anyway to assert the returned type because TypeScript can’t infer the type of dynamically fetched data. So destructuring the data is more dangerous than defensive coding (like using the optional chaining operator or good-old if statements).

Optional chaining or null checks should not be used "defensively". They should just be used whenever TypeScript tells you to. Otherwise you just exacerbate the problem and end up with more unanticipated null values.

If you're dealing with an API with untrustworthy types or lots of null values, the solution is to:

a) Write mostly optional type definitions for that API, and/or

b) Use zod to verify the API data before you use it, to make sure it matches your expectations.

https://github.com/colinhacks/zod




> Optional chaining or null checks should not be used "defensively"

Agreed. I often find the `Uncaught TypeError: Cannot read properties of null` error annoying. But I would rather see the error than let unknown nulls sneak through my codebase.


Quite often the best thing to do is:

1. Wait until TS complains about a possible null

2. If you have a good default value, use that instead

3. If not, throw a meaningful error

Either way, don't propagate the nulls further than they need to go.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: