Skip to content

Union with a mapped string template results in an unexpected type #50120

Closed
@cboar

Description

@cboar

Bug Report

🔎 Search Terms

union template string literal unexpected behavior

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about unions leading to unexpected behavior.

⏯ Playground Link

Playground link with relevant code

💻 Code

type A = { [P in `/${string}`]: string };
type B = { [P in 'one' | 'two' | 'three']: number };
type C = A | B;

// should not allow partial! But it is accepted, why?
const bug1: C = { one: 1 };
// should not be able to mix A and B! But it is accepted, why?
const bug2: C = { one: 1, '/hello': 'world' };

🙁 Actual behavior

Observe the mapped type A that uses a string template as an index, allowing only specific strings to be used as a key. When this type is used as part of a union, the resulting type exhibits behavior I found strange.

🙂 Expected behavior

I would expect the type assignment for bug1 and bug2 to not be permitted.

Activity

MartinJohns

MartinJohns commented on Aug 1, 2022

@MartinJohns
Contributor

Duplicate of #20863. Both your object literals are compatible with the type A, so assigning is permitted.

cboar

cboar commented on Aug 1, 2022

@cboar
Author

Thanks, I wasn't aware of this fact: Unions without discriminant properties do not perform excess property checking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @MartinJohns@cboar

        Issue actions

          Union with a mapped string template results in an unexpected type · Issue #50120 · microsoft/TypeScript