TypeScript - Nullish expression

less than 1 minute read

For the following type, we want to get val.value but if it is null or undefined, it should be 10.

1
2
3
4
5
type Value = {
  value? = 0 | 10 | 20
}

const val : Value = 0

For this solution, the following expression is always better

1
const res = val.value ?? 10

than

1
const res = val.value || 10

This is because if val.value = 0, it will return 10, which is not intended.