Skip to content

Wrong local variable type when assigned in lambda.Β #61313

Closed as not planned
Closed as not planned

Description

πŸ”Ž 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.

Activity

  1. MartinJohns commented on Feb 27, 2025

    @MartinJohns
    Contributor
  2. Danielku15 commented on Feb 27, 2025

    @Danielku15
    Author

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

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions