I need to check the textAreaRef.current
and textAreaRef.current.resizableTextArea
for undefined
value.
That works:
if (textAreaRef.current && textAreaRef.current.resizableTextArea) {
const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart;
}
But that don’t:
function isTextAreaExists() {
return textAreaRef.current && textAreaRef.current.resizableTextArea;
}
if (isTextAreaExists()) {
const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart;
}
TS18047: textAreaRef.current is possibly null
TS18048: textAreaRef.current.resizableTextArea is possibly null
Are there ways to simplify the expression?
2
Answers
It’s possible to preserve the type guard behavior of the original, but it seems cleaner to use more variables (and maybe the optional chaining operator
?.
).or if you don’t otherwise need
resizableTextArea
,This works
because Typescript is smart enough to also read the
if
statement and see if you have checked the parent object exist. However —textAreaRef.current && textAreaRef.current.resizableTextArea
doesn’t necessarily return a boolean value; it could be eitherfalse
, the value oftextAreaRef.current && textAreaRef.current.resizableTextArea
if it is valid ornull.
Becausetrue && 'Hello'
evaluates to'Hello'
.Also, if you store the
if
in a function, Typescript will not be able to tell if you are actually doing a safety check for your object or not, therefore throwing an error where the object you are using could potentially benull
.Here is a easy workaround by combining the power of optional chaining
?.
or even simpler
Using ternary here with
fallback
value is because you do not really want to declare a value inside aif
, since it will make the variable outside of theif
statement.Cheers!