I have a simple function in component:
const Button = ({text}: Props) => {
const {t, ready} = useTranslation();
const [title, setTitle] = useState('');
useEffect(() => {
if (ready) {
const btnText = text?.length > 0 ? text : 'button.default_text';
setTitle(btnText);
}
}, [ready]);
return <button>{t(title)}</button>
}
interface Props{
text?: string;
}
After switching on strictNullChecks
, typescript started complaining about 'text.length' is possibly 'undefined'.
Yes, because text
is optional prop text.length
could be undefined
, but I’m using a ternary operator.
When checked in console I got:
undefined.length > 0
VM904:1 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at <anonymous>:1:11
While with ternary:
undefined?.length > 0
false
Which means that in both cases expression will be either true
or false
. Why typescript complains and is it possible to fix it without using old school text && text.length > 0
?
2
Answers
What you are referring to is called Optional Chaining.
What you need though is called the non-null assertion operator, the exclamation point:
undefined!.length > 0
You could provide a default empty array in cases where
text
is undefined by using(text ?? []).length > 0 ?
.Why are you opposed to using
text && text.length > 0 ?
? This works too.