Skip to content

Better type check when using array + union #28981

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

Closed
macabeus opened this issue Dec 12, 2018 · 4 comments
Closed

Better type check when using array + union #28981

macabeus opened this issue Dec 12, 2018 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@macabeus
Copy link

macabeus commented Dec 12, 2018

Search Terms

type check
array
union

Suggestion

If we define a type like [null, string] | [number, null], we know that, if the first element is null, the second element is string, and if the second element is null, the first element is number. But, the type check can't understand it, what is less accurate than desired.

Use Cases/Example

When we creating a new function, we could want to return a value that is returned in success case, or an error if it failed. A simple way to do it is using an array, for example:

const createUser = (): [User, null] | [null, Error]  => {
  ...

Then, this function can return [User, null] or [null, Error]. But, the type check can't work very well:

const [user, error] = createUser()
if (user === null) {
  console.log(error.message) // type check mark a warning where, 
                             // saying that "error" could be null, but it is impossible!
  return
}

// type check say that "user" never will be null. It is ok.

or...

const [user, error] = createUser()
if (error !== null) {
  console.log(error.message) // no warning
  return
}

// type check say that "user" could be null, but it is impossible
@jack-williams
Copy link
Collaborator

I think this is a duplicate #27497 (and others). Narrowing does not work across destructuring like this.

@weswigham weswigham added the Duplicate An existing issue was already created label Dec 12, 2018
@macabeus
Copy link
Author

@jack-williams @weswigham Does we have an issue or pull request which we can track the fix about this issue?

@weswigham
Copy link
Member

I think #12184 is the canonical one.

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants