skip to Main Content

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


  1. 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 ?.).

    const resizableTextArea = textAreaRef.current?.resizableTextArea;
    
    if (resizableTextArea != null) {
      const currentCursorPosition = resizableTextArea.textArea.selectionStart;
    }
    

    or if you don’t otherwise need resizableTextArea,

    const textArea = textAreaRef.current?.resizableTextArea?.textArea;
    
    if (textArea != null) {
      const currentCursorPosition = textArea.selectionStart;
    }
    
    Login or Signup to reply.
  2. This works

    if (textAreaRef.current && textAreaRef.current.resizableTextArea) {
      const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart;
    }
    

    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 either false, the value of textAreaRef.current && textAreaRef.current.resizableTextArea if it is valid or null. Because true && '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 be null.

    Here is a easy workaround by combining the power of optional chaining ?.

    const currentCursorPosition = !!textAreaRef.current?.resizableTextArea?.textArea?.selectionStart
      ? textAreaRef.current?.resizableTextArea?.textArea?.selectionStart
      : fallbackvalue
    

    or even simpler

    const currentCursorPosition = textAreaRef.current?.resizableTextArea?.textArea?.selectionStart || fallbackvalue
    

    Using ternary here with fallback value is because you do not really want to declare a value inside a if, since it will make the variable outside of the if statement.

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search