0

When I'm checking if object is declared directly it works just fine obviously, but I'm wondering if it's possible to extract this check into a variable and make TypeScript to still understand it.

import React from "react";

interface Props {
  obj?: {
    val: string;
  }
}

function A({ obj }: Props) {
  const hasObj = !!obj;

  return (
    <>
      <p>This works fine:</p>
      <div>{!!obj && obj.val}</div>

      <p>This throws an error (Object is possibly 'undefined'):
      <div>{hasObj && obj.val}</div>
    </>
  )
}

Is it possible to make it work that way?

3
  • 1
    why not just use <div>{obj?.val}</div> ? Commented Jun 23, 2020 at 20:13
  • it's just a simple example, I need it for more complex checks Commented Jun 23, 2020 at 20:16
  • Consider trying type predicates. They only work with functions, but they might help you. typescriptlang.org/docs/handbook/… Commented Jun 23, 2020 at 20:16

1 Answer 1

1

As far as I understand it, TypeScript isn't smart enough to "follow" variables like that, i.e. that hasObj would always mean that !!obj unless something mutates or reassigns obj in the meanwhile.

If it suits your program, you can do a guard like

function A({ obj }: Props) {
  if (obj === undefined) {
    return;
  }

  return (
    <>
      <p>This works fine:</p>
      <div>{obj.val}</div>

      <p>This throws an error (Object is possibly 'undefined'):
      <div>{obj.val}</div>
    </>
  )
}

which does work, and TypeScript correctly infers obj can't possibly be null past that early return.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.