Is it possible that type-safety is compromised in TypeScript when dealing with JSON parsing?
I should be triggering an error, but I'm not:
interface Person {
name: string
}
const person: Person = somePossibleFalsey ? JSON.parse(db.person) : undefined
In the above scenario, there should be a type check failure, but surprisingly, there isn't. The db.person
may be missing, resulting in person
being set to undefined
. However, Person
should never be equal to undefined
. This anomaly seems to be connected to the usage of JSON.parse
.
To confirm the expected error output, here is another code snippet which correctly flags an error:
const person: Person = Math.random() > .5 ? { name: 'Arthur' } : undefined
The aforementioned code triggers the appropriate TypeScript error message:
Type '{ name: string; } | undefined' is not assignable to type 'Person'.
Type 'undefined' is not assignable to type 'Person'.ts(2322)
Why does JSON.parse
seem to bypass type-safety measures? Is there another underlying issue at play here?