Skip to content

(T | undefined) & T has different behavior when T is known versus when T is a type variableΒ #46976

Closed
@TheUnlocked

Description

@TheUnlocked

Bug Report

πŸ”Ž Search Terms

  • or undefined
  • and undefined
  • undefined generic disjunction
  • generic or undefined

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

// Samples of behavior on known types
// The evaluated type is always equal to the input type
type Test1 = (1 | undefined) & 1; // 1
type Test2 = (string | undefined) & string; // string
type Test3 = ({ a: 1 } | undefined) & { a: 1 }; // { a: 1 } & { a: 1 }
type Test4 = (unknown | undefined) & unknown; // unknown
type Test5 = (never | undefined) & never; // never

// Minimal example of issue
function f<T>() {
    type Y = (T | undefined) & T; // (T | undefined & T)
}

// Minimal example of when this could cause a problem
function g1<T extends {}, A extends { z: (T | undefined) & T }>(a: A) {
    const { z } = a;

    return {
        // T must extend {} so it should be spreadable
        // ERROR: Spread types may only be created from object types. (2698)
        ...z
    };
}

// If the type of z is just T instead of (T | undefined) & T, it works fine
function g2<T extends {}, A extends { z: T }>(a: A) {
    const { z } = a;

    return {
        ...z
    };
}

πŸ™ Actual behavior

The type expression (T | undefined) & T evaluates to itself when T is a type variable.

πŸ™‚ Expected behavior

Either (T | undefined) & T should evaluate to T when T is a type variable since that's the behavior with known types, or (T | undefined) & T should not evaluate to T when T is a known type (and should instead evaluate to something else in both cases-- never maybe?).

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions