This come with a debate with my colleague that I'm using nullable object type.

  type Value = Node | null
  const [v0, setV0] = React.useState<Value>(null)
  const [v1, setV1] = React.useState<Value>(null)

  const snapshot = (nodes: Node[]) => {
    const root = Parser.parse(nodes)
    if (v0 === null) {
    } else if (v1 === null) {
    } else {
    alert("current version saved!")

He's suggestion is change it to undefinable object type. type Value = Node | undefined since null is a mistake

My understanding with undefined type in JS is a preserve type for item not found. ie,

object['not exist'] === undefined
array[-1] === undefined

With his suggestion we cannot distinguish if

type object = { [key: string]: Value }
object['not exist'] === undefined
const a: Value = object['not exist']

Also many libraries like lodash treat undefined and null differently. So I'm worried if this can cause problems later on.

  • 3
    If null is a mistake, then Node | undefined is the same sort of a mistake, for the same reason - it's only that it's slightly different in flavor. So your colleague's argument kind of doesn't hold up. But see what semantically makes more sense - null or undefined - and consider how your type is going to be used. Jul 27, 2020 at 4:20
  • 1
    Undefined is a variable that has been declared but not assigned a value. null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, it's type is undefined.use according to how your variable type is.
    – AjayGohil
    Jul 29, 2020 at 7:22

1 Answer 1


Undefined usually signifies that a property does not exist at all. For example, as you showed, attempting to access a missing property yields undefined. This is because the property itself does not exist; it is not valid.

Null on the other hand signifies that a property exists, but has no value. If it is legal within your program for a value to be optionally present (which appears to be the case in your specific example), then go with null since that better communicates that the property exists but is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.