Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Either or type but not null

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

Answers (1)

T.J. Crowder
T.J. Crowder

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 and undefined are assignable to any other type. This can make writing some code easier, but forgetting to handle null and undefined is the cause of countless bugs in the world - some consider it a billion dollar mistake! The strictNullChecks flag makes handling null and undefined more explicit, and spares us from worrying about whether we forgot to handle null and undefined.

Upvotes: 2

Related Questions