-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Intersection type with discriminated union type that includes all possible enum values cannot accept enum type #33654
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
Labels
Milestone
Comments
Looks to be a duplicate of #33243. |
Workaround
|
Shorter type Payload =
| { type: "A" }
| { type: "B" }
declare const type: "A" | "B";
// Should be OK, but errors
const id: { id: number } & Payload = { id: 0, type }; @rbuckton I think your PR to expand out possible types of unions should make this work - any idea why that's not happening? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In TypeScript you can create a union type discriminated by an
enum
. If the union includes all possibleenum
values, you can create it with a value that is typed to theenum
(not one of its values).Given my example below, this is valid:
const p: Payload = { type, value }
When you create a new type by intersecting the discriminated union type with another type definition, for example to add another field, this no longer works. It is now no longer possible to assign a value that is typed to the
enum
to the new type.So this is invalid:
const p: { id: string } & Payload = { id, type, value }
The workaround I can think of is the following, but it's pretty tedious:
TypeScript Version: 3.6.3
Search Terms: intersection discriminated union enum
Code
Expected behavior: Works
Actual behavior:
Type '{ id: string; type: Type; value: any; }' is not assignable to type 'IdentifiedPayload'.
Playground Link: https://www.typescriptlang.org/play/index.html#code/KYOwrgtgBAKgngB2FA3gKClAUgewJYhQC8UARAFb4ikA0GUAMsAIYBuyJpANi+7fQFlgAZ2HMA5hzIQRYyf0wB1YFwDGOGcTIB3Fepmk0AXzRoALomQAFZnC45mAE2L0APqigWkALliWAdLgEANxQrMxcYMC+KFAgeKoA1iDMMr7CZgBOBOJQRnluHl7Rfkj+TGzAoeGRJSj5JpjuscW+8GVCohJVYRFRMVAyXZLpWTl5BU2o9JiYraXA-spqGlUzszX9HjhmABbAmcIDeI6j2SDiofFJKWlQGee5RgDaALp5wetGn+aWUACSjlAZjwADM8MBHDY7A5nCRYiczuN8gAyKDQ+xOH6gsAgVQgnCEBDMQ7AAAUjmYZmYSIuAEpfIDgWCIVDbJjnOhMOoQBkoM8TjRPJYheRhIT3iRKdT-MIEFw8GYyaQyEKAMx0z6YMFQMnFHCgqBiwlQACERE4DxypDpnl2mRw2igAFFMg7MsrMsBVMA8OxnAQaicoNLmDatVAdWTTXhhO1ycU6ba9g6na73crAxFg8UyFAANTCpCa+g8vmbKRYADKAHkAHL+YmksnGkAlzBesxgTKEBGOIXFIUVj7GUw4vEEwix+N6yy08QMovIWMLaYd4BdntQGsAI3I3rM-grwjJ8bp-gIqkiQJPic+JiAA
Related Issues:
The text was updated successfully, but these errors were encountered: