Skip to content

Value of type T is not assignable to T & U even when T extends U #33340

Closed
@Muon

Description

@Muon

At least in the case of U being a nonempty finite union of singleton types, it seems that T extending U does not imply that T is assignable to T & U, even though every value of type T is also a value of type U.

However, the distributive conditional type T extends U ? T : never is considered assignable to U even though it should have the same set of values as T since we assume that T extends U.

TypeScript Version: 3.5.1 and 3.7.0-dev.20190907

Search Terms: enum intersection extends not reduced

Code

type A = 1 | 2;
function f<T extends A>(a: T): A & T  { return a; } // Error: Type '1' is not assignable to type '2'.
function g<T extends A>(a: T extends A ? T : never): A & T  { return a; } // OK

Expected behavior: Compiles.

Actual behavior: Does not compile.

Playground Link: https://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAglC8UCMUA+UBMBuAUAMwFcA7AY2AEsB7IqPAHgBUoIAPYCIgEwGdYA+ABQBDAFxQGASjFwAZOKhQA3lABOEYARU0hWKAF8gA

Related Issues: #28830

For context, I am attempting to write a function that takes a union tag and a payload and returns a matching new instance of one of the members of a tagged union.

Here is some further exploration in that direction: https://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAglC8UCMUA+UBMBuAUAMwFcA7AY2AEsB7IqPAHgBUoIAPYCIgEwGdYA+ABQBDAFxQGASjFwAZOKhQA3lABOEYARU0hWKAF98xMlRoBzRszYce-YWKat2XXnAD88sUQgA3CCqmwUHJMSqrqmtq6BjjkROwqeEIk0ACySjgKCqLIuAax8YnJUABy6ZlQ2dg40YSkFNRQABYWjtYugtmSYgIpqMUSQUqdegrKahpaQ3pRhnUmUOQtVs62nZZONm4eUF6+-t29-YOKw6NhEzQn0-pQs8YNAFZLG+12Q-YjrSuHUO5Mnj4-AEen0BnITh8zuMIlMZrV7jQANbPNqBDr2daorb-HaA-bvcSfZY2EFHdwQhgjcGnAF7ULQyZXOFGeo0AA2KJWMHRBMpmJWpLBvJGv22uyBB1Bx1O9PCjKE1z0QA

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions