Skip to content

Typescript 5.0.2 does not infer type correctly with React.isValidElement #53348

Closed
@changwoolab

Description

@changwoolab

Bug Report

import React from "react";

type B = {
  b1: string;
  b2: number;
};

export function type(input: React.ReactElement | string | B) {
  if (typeof input === "string") {
    return input;
  }

  if (React.isValidElement(input)) {
    return input;
  }

  return input.b1;
}

After running tsc in the console, I got this error.

Screenshot 2023-03-19 at 5 27 09 PM

But there was no error in VScode and type inference was working well
Screenshot 2023-03-19 at 5 29 43 PM

Also, there was no error with 4.9.4.

🔎 Search Terms

typescript 5.0, React, ReactElement, isValidElement, inference, deduce

🕗 Version & Regression Information

After upgrading to typescript 5.0.2 and running tsc in the console.

  • This is a crash
  • This changed between versions 4.9.4 and 5.0.2
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

⏯ Playground Link

Playground link with relevant code

💻 Code

import React from "react";

type B = {
  b1: string;
  b2: number;
};

export function type(input: React.ReactElement | string | B) {
  if (typeof input === "string") {
    return input;
  }

  if (React.isValidElement(input)) {
    return input;
  }

  return input.b1;
}

🙁 Actual behavior

Type of input at the last line was B | ReactElement

🙂 Expected behavior

Type of input at the last line should be B

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions