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

Conflicting eslint rules re: TypeScript non-null assertions #981

Closed
lindapaiste opened this issue Jun 15, 2021 · 1 comment
Closed

Conflicting eslint rules re: TypeScript non-null assertions #981

lindapaiste opened this issue Jun 15, 2021 · 1 comment

Comments

@lindapaiste
Copy link

I decide to work on #494 and I've come across a case of conflicting eslint rules. Of course I could eslint-disable-next-line, but I think it would be better for this project to have a standard of how it handles type assertions.

The problematic function is this:

function onDone(error: Error | null, result: T | null) {
  finished = true
  clearTimeout(overallTimeoutTimer)

  if (!usingJestFakeTimers) {
    clearInterval(intervalId)
    observer.disconnect()
  }

  if (error) {
    reject(error)
  } else {
    resolve(result!)
  }
}

I initially wrote resolve(result as T), but this caused an error

122:13 error Use a ! assertion to more succintly remove null and undefined from the type @typescript-eslint/non-nullable-type-assertion-style

So I used the ! as recommended and wrote resolve(result!), but then I got an error telling me not to

122:13 error Forbidden non-null assertion @typescript-eslint/no-non-null-assertion

The reason that this needs an assertion is the questionable assumption that if error is null then result must be a value. When looking at this function in isolation it's not a safe assumption because error and result are two unrelated variables. In the context of the file you can see that one is always null, so then it's ok to assert.

Of course there are ways to restructure the code to avoid the need for the assertion, but it seems like that is not desired based on this comment. This is a pretty simple assertion, I'm just unsure of which syntax is preferred.

@lindapaiste lindapaiste changed the title Conflicting eslint rules re: TypeScript assertions Conflicting eslint rules re: TypeScript non-null assertions Jun 15, 2021
@eps1lon
Copy link
Member

eps1lon commented Jun 16, 2021

Thanks for the work!

You can use @typescript-eslint/no-non-null-assertion and add a comment why the non-null assertion is correct. TypeScript is unaware of some assumptions so we have to provide these to explain to the compiler what's happening.

@eps1lon eps1lon closed this as completed Jun 16, 2021
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