-
Notifications
You must be signed in to change notification settings - Fork 13.3k
(T | undefined) & T has different behavior when T is known versus when T is a type variableΒ #46976
Copy link
Copy link
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
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?).
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue