Skip to content

Instantly share code, notes, and snippets.

@romgrk
Last active October 5, 2023 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romgrk/8ebbd1590d8e0998d448fcd09e789a26 to your computer and use it in GitHub Desktop.
Save romgrk/8ebbd1590d8e0998d448fcd09e789a26 to your computer and use it in GitHub Desktop.
Avoiding nullable types

I've been seeing this pattern quite a bit:

// inside a component
const dimensions = useRef<DOMRect | null>(null)

useEffect(() => {
  dimensions.current = someRef.current.getBoundingClientRect()
}, []);

The problem with nullable types like DOMRect | null is that they tend to propagate throughout the codebase, and end up forcing everywhere else to handle nullability. We end up with 10s of if (dimensions && ...) or dimensions?.width ?? 0 that could be avoided. Being able to get rid of the | null part of the type right away simplifies the rest of the codebase.

The pattern could instead be replaced with:

// static constant, outside the component
const EMPTY_DIMENSIONS = new DOMRect(0, 0, 0, 0)

// inside a component
const dimensions = useRef(EMPTY_DIMENSIONS)
// etc

In the rare cases where being able to tell if initialization has happened (which are much rarer than simple usages of the value), then we can easily:

const didInitialize = dimensions !== EMPTY_DIMENSIONS

Alternatively, we can also attach a flag directly on the type:

const EMPTY_DIMENSIONS = { isInitialized: false, width: 0, height: 0 }
// etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment