You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Property ... is missing in type ... but required in type ... when uncertainty is introduced during assignment to variable of discriminated union type #54676
typeA=|{prop: {type: "number";num: number;str?: undefined;};}|{prop: {type: "string";num?: undefined;str: string;};};// Expected: No error// Actual: Property 'str' is missing in type '{ type: "number"; num: number; }' but required in type '{ type: "string"; num?: undefined; str: string; }'.consta: A={prop:
// Introducing uncertainty in the assignment// appears to be key to triggering this bugMath.random()>0.5
? {type: "string",str: "hello",}
: {type: "number",num: 123,},};
🙁 Actual behavior
Type '{ prop: { type: "string"; str: string; } | { type: "number"; num: number; }; }' is not assignable to type 'A'.
Type '{ prop: { type: "string"; str: string; } | { type: "number"; num: number; }; }' is not assignable to type '{ prop: { type: "string"; num?: undefined; str: string; }; }'.
Types of property 'prop' are incompatible.
Type '{ type: "string"; str: string; } | { type: "number"; num: number; }' is not assignable to type '{ type: "string"; num?: undefined; str: string; }'.
Property 'str' is missing in type '{ type: "number"; num: number; }' but required in type '{ type: "string"; num?: undefined; str: string; }'.
In general, { foo: A | B } is not assignable to { foo: A } | { foo: B } (there are some exceptions, but that's the general rule). This happens to be safe with one property, but not when there are multiple. Since the uncertainty is specifically in the value of prop and not the entire object, the structure of the type should reflect that.
I guess this could be done with even more type variables or Extract instead but I find the lack of intellisense (vscode) on the second type parameter makes Extract a bit unfriendly/unsafe to use.
Activity
fatcerberus commentedon Jun 16, 2023
In general,
{ foo: A | B }is not assignable to{ foo: A } | { foo: B }(there are some exceptions, but that's the general rule). This happens to be safe with one property, but not when there are multiple. Since the uncertainty is specifically in the value ofpropand not the entire object, the structure of the type should reflect that.FelixZY commentedon Jun 16, 2023
I see. For this particular case I wanted very specifically to have a single property and to do
I guess this could be done with even more type variables or
Extractinstead but I find the lack of intellisense (vscode) on the second type parameter makesExtracta bit unfriendly/unsafe to use.EDIT:
Solved this by doing:
fatcerberus commentedon Jun 16, 2023
You could write it like this: