Skip to content
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

Type Intersection incorrect for optional parameters in functions with exactOptionalPropertyTypes: true. undefined type is flip based off Intersection types #58174

Open
JDMathew opened this issue Apr 12, 2024 · 0 comments · May be fixed by #58186
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@JDMathew
Copy link

This issue seem to only be related when exactOptionalPropertyTypes: true option is set

If I have:

type A = {
  disabled?: boolean;
};

type B = {
  disabled?: boolean | undefined;
};

type C = {
  disabled?: boolean;
};

type AB = A & B;
type AC = A & C;

const fnA = ({disabled}: A) => {
  disabled //disabled: boolean | undefined
};

const fnB = ({disabled}: B) => {
  disabled //disabled: boolean | undefined
};

// case AB is incorrect in this function!
const fnAB = ({disabled}: AB) => {
  disabled //disabled: boolean 
};

const fnAC = ({disabled}: AC) => {
  disabled //disabled: boolean | undefined
};

Consider fnA, since a property that is optional may be undefined when it is called it makes sense that undefined is added to the type, as is in the case in fnA // disabled: boolean | undefined. (fnB example added for completeness).

Now consider fnAB with the intersection type AB, property disabled type should also be // disabled: boolean | undefined but it is not, instead it is // disabled: boolean

Finally fnAC with the intersection type AC, the property disabled type is now correct being // disabled: boolean | undefined.

It seems like in the above example with fnAB (intersection of AB) the undefined's are canceling out since undefined is added with the ? optional parameter. A similar issue can be observed with two undefined such as { disabled?: boolean | undefined; } && { disabled?: boolean | undefined; } would result in //disabled: boolean

It's worth noting this doesn't seem to only be limited to function parameter de-structuring since a similar issue is seen in:

// incorrect
function fnAB(props: AB) {
  props.disabled //disabled?: boolean
}

// correct
function fnAC(props: AC) {
  props.disabled //disabled?: boolean | undefined
}

When exactOptionalPropertyTypes: false property disabled is always disabled //disabled: boolean | undefined which is correct

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
2 participants