When working with ReactJS, I often find myself using a common pattern of destructuring props:
export default function Example({ ExampleProps }) {
const {
content,
title,
date,
featuredImage,
author,
tags,
} = ExampleProps || {};
To add an extra layer of safety, I can set default values during the destructuring process:
export default function Example({ ExampleProps }) {
const {
content = "",
title = "Missing Title",
date = "",
featuredImage = {},
author = {},
tags = [],
} = ExampleProps || {};
However, after transitioning to TypeScript strict
mode, I encountered some difficulties. My props are typed using GraphQl codegen, and most properties are wrapped in a Maybe<T>
type, resulting in values like actualValue | null | undefined
when unwrapped.
To address cases where the value is undefined
, I used default values
. However, issues arose with ({ maybeUndefined = ""} = props)
null
values slipping through, leading to numerous instances of optional chaining like tags?.nodes?.length
.
This reliance on optional chaining made me apprehensive, especially considering discussions about its drawbacks highlighted in articles such as The Costs of Optional Chaining.
I am now seeking a pattern, potentially utilizing the ??
operator, that satisfies the TS compiler while reducing the need for lengthy chains such as very?.long?.optional?.chains
.