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

TypeScript incorrectly detects nullable when using Required operator #61275

Closed
LeHibouMT opened this issue Feb 26, 2025 · 1 comment
Closed

Comments

@LeHibouMT
Copy link

🔎 Search Terms

"Required", "Undefined"

🕗 Version & Regression Information

  • This changed between versions 5.7.2 and 5.7.3
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Required Operator
  • I was unable to test this on prior versions because I lacked times

⏯ Playground Link

https://playcode.io/2273403

💻 Code

interface Link {
path: string;
label: string;
subLinks?: [Link, ...Link[]]; // either undefined or defined with at least one element
}

let testRequiredArray: Required[] = [];

const testArray: Link[] = [
{ path: '1', label: '1' },
{ path: '2', label: '2', subLinks: [{ path: '3', label: '3' }] },
];

testArray.map(link => {
if (!link.subLinks) {
console.log('no sublinks!');
} else {
console.log('sublinks!');
// error
testRequiredArray = [...testRequiredArray, link];
// but this work as typescript knows that sublinks is defined and have at least one element
let test = link.subLinks[0];
}
});

🙁 Actual behavior

TypeScript doesn't detect in the "if" block that a value should be defined so it leads to an error when trying to use it for a Required variable.

I have the error: Type 'Link' is not assignable to type 'Required'.
Types of property 'subLinks' are incompatible.
Type '[Link, ...Link[]] | undefined' is not assignable to type '[Link, ...Link[]]'.
Type 'undefined' is not assignable to type '[Link, ...Link[]]'.ts(2322)

🙂 Expected behavior

TypeScript should detect that its defined.

Additional information about the issue

I used it with React but the same error appears with regular TypeScript code.

@MartinJohns
Copy link
Contributor

Duplicate of #42384.

  • This changed between versions 5.7.2 and 5.7.3

I doubt that this is true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants