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

(compiler api) Is it possible variable used before assigned if overridden with non-null operator? #31124

Closed
bradzacher opened this issue Apr 26, 2019 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@bradzacher
Copy link
Contributor

bradzacher commented Apr 26, 2019

We have a lint rule which attempts to check if a non-null assertion operator is required or not, and warns against the unnecessary operator.

We've essentially got this check in place currently:

const type = checker.getTypeAtLocation(nonNullNode.expression);
if (type === checker.getNonNullableType(type)) {
  reportAndFix('non-null assertion is not required');
}

Which works for every case I can think of, except for the "use before assigned" case.
In that case the type returned by the checker is non-null unless the original variable declaration includes a nullable type.
In this case, the type is considered non null, and the identifier is considered not yet assigned.

Example code:

function testRequired() {
    let resolve: () => void
    new Promise(resolve0 => {
        resolve = resolve0
    })
    return resolve! // this non-null assertion is required, removing it causes compiler to hard fail
}

function testNotRequired() {
    let resolve: () => void = () => {}
    new Promise(resolve0 => {
        resolve = resolve0
    })
    return resolve! // this non-null assertion is not required, removing it is fine
}

I'm trying to figure out if it's possible to detect (using the type checker or similar) that the non-null operator is truly required because the variable is being used before it is assigned.

If we can't detect this case, then we can't provide an autofixer (and I'd really like to provide a fixer), because otherwise in this case we fix to non-compiling code.

related: typescript-eslint/typescript-eslint#453

@AlCalzone
Copy link
Contributor

@ajafff
Copy link
Contributor

ajafff commented Apr 26, 2019

Duplicate of #20221

In the meantime I implemented a workaround in my lint rule (link above). It's pretty limited though and doesn't analyze the control flow graph.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants