Skip to content
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

Allowing union types to work on control flow analysis #46322

Closed
5 tasks done
max-hk opened this issue Oct 12, 2021 · 4 comments
Closed
5 tasks done

Allowing union types to work on control flow analysis #46322

max-hk opened this issue Oct 12, 2021 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@max-hk
Copy link

max-hk commented Oct 12, 2021

Suggestion

πŸ” Search Terms

  • Control flow analysis
  • Union types

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

It would be better if we allow union types to work on control flow analysis

πŸ“ƒ Motivating Example

type Shape =
    | { kind: "circle", radius: number }
    | { kind: "square" | 'rectangle', sideLength: number };

function area(shape: Shape): number {
    if (shape.kind === "square" || shape.kind === "rectangle") {
        // We know we have a square/rectangle here!
        return shape.sideLength ** 2;
    }
    else {
        // We know we 're left with a circle here!
        // But TypeScript failed to recognize it
        return Math.PI * shape.radius ** 2;
    }
}

πŸ’» Use Cases

@MartinJohns
Copy link
Contributor

Playground link

@MartinJohns
Copy link
Contributor

MartinJohns commented Oct 12, 2021

This sounds like a duplicate of #31404. See this comment for a workaround.

@andrewbranch
Copy link
Member

I retitled that issue since it wasn't actually related to undefined.

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Oct 12, 2021
@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

4 participants