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

Issues with type narrowing in if-else statements #28

Closed
abhayvatsa opened this issue May 22, 2021 · 5 comments
Closed

Issues with type narrowing in if-else statements #28

abhayvatsa opened this issue May 22, 2021 · 5 comments

Comments

@abhayvatsa
Copy link

abhayvatsa commented May 22, 2021

Hi there!

Thanks for making this, been enjoying this library.

I am running into an issue with the type narrowing for if-else statements. I'm not sure if I'm doing something wrong, but this issue was mentioned in #5. I expect that a type guard on result.ok would narrow the union type appropriately in the else block. Instead I see an error like this:
Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.

Currently on typescript 4.2.4

Here are two examples that are more or less the same.

import { Ok, Err } from 'ts-results'

const result = Ok(1) as Ok<number> | Err<string>

if (result.ok) {
  const val: number = result.val
} else {
  const val: string = result.val
}
import { Ok, Result } from 'ts-results'

const result = Ok(1) as Result<number, string>

if (result.ok) {
  const val: number = result.val
} else {
  const val: string = result.val
}
@vultix
Copy link
Owner

vultix commented May 23, 2021

Alright, I think I've tracked this one down. As far as I can tell, the type narrowing only works when strictNullChecks is turned on in your tsconfig file.

Will you try turning on strictNullChecks and let me know if that fixes the issue? I'm guessing this is a bug in the typescript compiler itself

@vultix
Copy link
Owner

vultix commented May 23, 2021

Here's a super simple replication in the typescript playground

@vultix
Copy link
Owner

vultix commented May 23, 2021

Looks like this is a known bug: microsoft/TypeScript#10564

@abhayvatsa
Copy link
Author

@vultix. Wow, thanks this worked. Appreciate the fast response. Would it make sense to make a note of this somewhere in the docs?

@vultix
Copy link
Owner

vultix commented May 23, 2021

I added a note in the README. I'm going to close this issue for now, hopefully this gets fixed in Typescript soon

@vultix vultix closed this as completed May 23, 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