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 narrowing not work in forEach callback #58707

Closed
xiaoxiyao opened this issue May 30, 2024 · 2 comments
Closed

Type narrowing not work in forEach callback #58707

xiaoxiyao opened this issue May 30, 2024 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@xiaoxiyao
Copy link

πŸ”Ž Search Terms

narrow forEach

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about "common-bugs-that-arent-bugs"

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.4.5#code/FAGwpgLgBAZg9nAXFAzhATgSwHYHMoA+UAguugIYCeAPGlngHwDcww8cUAvFANoC6LNggB0ABwCuKABYAKAORyAlEygB6VXADWrAMZxsaKOTJdec8nIA0UOQCMrNnXIGt46KDL0HoKKHBhGZIpQAN7AUBGwIhLSMijKaqpR7v5QmL5awAC+rMbowm4AouQ6sr6cDKHhkexikmUJ6lBgZHDo2cqsmAEypBSUwul9VDLsisFhkYH5RSVlXJWTUzXR9XGNSS3obdURWZ05bOLYOhCY+lAQYGgyE7tRcHWxChvNrejWALZUtmBQ2HBoAB3NqaNLYWDHU7nCEAfmywCAA

πŸ’» Code

let foo: string | Array<string>;

foo = [];

foo.push(''); //ok

const arr = ['a', 'b', 'c'];

for (const s of arr) {
    foo.push(s); // for of is ok
}

arr.forEach(s => {
    foo.push(s); // error
});

if (Array.isArray(foo)) {
    arr.forEach(s => {
        foo.push(s); // error
    });
}

function test() {
    foo.push(''); // error, maybe not work in function ?
}

πŸ™ Actual behavior

Type narrowing not work in forEach callback

πŸ™‚ Expected behavior

Type narrowing work as expected

Additional information about the issue

No response

@fatcerberus
Copy link

error, maybe not work in function ?

Correct - see #9998.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 6, 2024
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants