In ReactJS, I commonly use this pattern of destructurnig props (I suppose it is quite idiomatic):
export default function Example({ ExampleProps }) {
const {
content,
title,
date,
featuredImage,
author,
tags,
} = ExampleProps || {};
I can add default values while destructuring, which adds some safety:
export default function Example({ ExampleProps }) {
const {
content = "",
title = "Missing Title",
date = "",
featuredImage = {},
author = {},
tags = [],
} = ExampleProps || {};
But now I switched to TypeScript strict
mode and I have quite a hard time. My props are typed by GraphQl codegen, and virtually all the properties are wrapped in a Maybe<T>
type, so when unwrapped, there are like actualValue | null | undefined
.
The default values ({ maybeUndefined = ""} = props)
can save me in case the value is undefined
, but the null
values would fall through, so the TS compiler is nagging and my code results in a lot of:
tags?.nodes?.length // etc…
which makes me a little nervous because of the The Costs of Optional Chaining article (although I don't know how relevat it still is in 2021). I've also heard ?.
operator overuse being referred as an example of "code smell".
Is there a pattern, probably utilizing the ??
operator, that would make the TS compiler happy AND could weed out at least some of that very?.long?.optional?.chains
?