Skip to content

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

@Danielku15

Description

@Danielku15

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

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