Skip to content

Wrong local variable type when assigned in lambda. #61313

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

Closed
Danielku15 opened this issue Feb 27, 2025 · 2 comments
Closed

Wrong local variable type when assigned in lambda. #61313

Danielku15 opened this issue Feb 27, 2025 · 2 comments

Comments

@Danielku15
Copy link

πŸ”Ž Search Terms

type, infer, lambda, callback

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.3#code/GYVwdgxgLglg9mABAgogJzXNAKAFgQzABMAbAUzQC5Fszr1M0BKRAXgD5EA3OGIlgN4BYAFCJxiAsXI4wZAO6IGWbEyYBuUQF9Ro8lEQVGlZWgA+YECRJtEl65pGjUGFWTadhYiUay2yjloauiIwwLSuaIgAhKysdlYkgqISiFC4mIq+aIGiQA

πŸ’» Code

function onError(handler: (e: Error) => void) {
    handler(new Error());
}

let error:Error|null = null;

onError(e => {
    error = e;
});

if(error !== null) {
    throw error;
}

πŸ™ Actual behavior

The type of error is inferred as null in line 11 and unknown in line 12. This is wrong because there is a potential assignment to error` in the local lambda.

πŸ™‚ Expected behavior

The type of error should be Error|null after the onError call as there is a potential assignment happening in the callback. Its understandable if the analyzer cannot widen the type if the passed callback is again some other function or method but for local lamdbas it could be treated like a "conditional" which might be met. e.g. in the following example error is widened to Error|null

function onError(handler: (e: Error) => void) {
    handler(new Error());
}

let error:Error|null = null;

if(Math.random() > 0.5) {
    error = new Error();
}

if(error !== null) {
    throw error;
}

Additional information about the issue

One workaround I currently have is to add error = error as Error | null; somewhere.

@MartinJohns
Copy link
Contributor

Duplicate of #9998. There's even a dedicated issue type for this: https://github.com/microsoft/TypeScript/blob/main/.github/ISSUE_TEMPLATE/types-not-correct-in-with-callback.md?plain=1

@Danielku15
Copy link
Author

Sorry, I have totally missed this. πŸ™‡β€β™‚ Textual searching is hardly possible anymore in this repository 😒

@Danielku15 Danielku15 closed this as not planned Won't fix, can't repro, duplicate, stale Feb 27, 2025
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