Skip to content

Typescript 4.8.4: Different type inference on two if branches with (fundamentally) identical input #52917

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
HynekS opened this issue Feb 22, 2023 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@HynekS
Copy link

HynekS commented Feb 22, 2023

Bug Report

πŸ”Ž Search Terms

πŸ•— Version & Regression Information

  • This changed between versions 4.7.4 and 4.8.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

import {
  Children,
  cloneElement,
  ReactElement,
  isValidElement,
} from "react";

type TestProps = {
  className?: string;
} & JSX.IntrinsicElements["div"];

export const Test = ({
  children,
}: TestProps) => {
  return (
    <div>
      {Children.map(children, (element) => {
        if (isValidElement(element) && Math.random() > 0.5) {
          const props = element.props || {};
          return cloneElement(element as ReactElement, {
            ...props,
            className: `someClassName ${props.className}`,
          });
        }
        if (isValidElement(element) && Math.random() < 0.5) {
          const props = element.props || {};
          return cloneElement(element as ReactElement, {
            ...props,
            className: `someClassName ${props.className}`,
          });
        }
        return element;
      })}
    </div>
  );
};

πŸ™ Actual behavior

The two if branches give different TS output (type inference & errors) with the same input (fundamentally same input; if identical input was used, the branching would not make sense. Demonstrating with Math.random()).

This behavior first appears in the TS playground in version 4.8.4. My project, where I ran into this issue, is also on v4.8.4. It seems to work as expected in earlier version 4.7.4.

ts-error

πŸ™‚ Expected behavior

The inferred types and errors will be identical in both branches with (fundamentally) identical input.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 22, 2023
@RyanCavanaugh
Copy link
Member

Duplicate of #52232

@RyanCavanaugh RyanCavanaugh marked this as a duplicate of #52232 Feb 22, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants