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

Object requires unnecessary type checking #42473

Closed
ChocolateLoverRaj opened this issue Jan 24, 2021 · 2 comments
Closed

Object requires unnecessary type checking #42473

ChocolateLoverRaj opened this issue Jan 24, 2021 · 2 comments

Comments

@ChocolateLoverRaj
Copy link

Bug Report

πŸ”Ž Search Terms

unnecessary type checking

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type checking

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export type Type = {
  type: 'a'
  data: {
    prop1: string
  }
} | {
  type: 'b'
  data: {
    prop1: string
    aPropThatTypeADoesNotHave: string
  }
}

export const shouldWorkButDoesNot = (o: Type): void => {
  o = {
    type: o.type,
    data: {
      ...o.data,
      prop1: 'updated value'
    }
  }
}

export const worksButSoUnnecessary = (o: Type): void => {
  o = o.type === 'a'
    ? {
      type: o.type,
      data: {
        ...o.data,
        prop1: 'updated value'
      }
    }
    : {
      type: o.type,
      data: {
        ...o.data,
        prop1: 'updated value'
      }
    }
}

πŸ™ Actual behavior

The shouldWorkButDoesNot function has a type error. It shouldn't have a type error because no matter what o.type is, ...o.data will always include the required props.

The function below (worksButSoUnnecessary ) works by type checking o.type, but since both parts of the ternary are exactly the same, the type checking is completely useless. However, it still needed?? for there to not be any typescript errors.

πŸ™‚ Expected behavior

The function shouldWorkButDoesNot should not have an error.

@jcalz
Copy link
Contributor

jcalz commented Jan 25, 2021

See #30581; o.type and o.data are correlated in a way the compiler does not understand unless you walk it through the different cases via control flow analysis.

@ChocolateLoverRaj
Copy link
Author

Duplicate of #30581

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