Reputation: 85545
I am having issue with typescript when using or operator it is accepting null value as well which I don't want:
interface Value1 {
name: string;
email: string;
}
interface Value2 {
id: string;
image: string;
}
Now, when using it:
val: Value1 | Value2
It should accept either Value1 or Value2 but it's also accepting null value. If I just do val: Value1
then doesn't accept null. So, how to avoid null value when using or operator?
Upvotes: 1
Views: 381
Reputation: 1074148
By default, null
and undefined
are assignable to any type. You need to enable strictNullChecks
to prevent that:
By default, values like
null
andundefined
are assignable to any other type. This can make writing some code easier, but forgetting to handlenull
andundefined
is the cause of countless bugs in the world - some consider it a billion dollar mistake! ThestrictNullChecks
flag makes handlingnull
andundefined
more explicit, and spares us from worrying about whether we forgot to handlenull
andundefined
.
Upvotes: 2