⬅️ Execute Program Advanced TypeScript
Validating data manually
- 💡
typeof null === 'object'
in both JavaScript and TypeScript.
Remember:
-
The JSON value might not be an object at all.
-
It might be
null
, which is an object in JavaScript but not the kind of object we expect. -
It might not have the
message
property that we expect. -
It might have a
message
, but with an unexpected type. -
💡 We can implement checks with a third-party data validation library like io-ts or runtypes.
-
💡 When using
JSON.parse
, it’s best to explicitly specify theunknown
type, likeconst parsed: unknown = JSON.parse(json)
.