Skip to content

Object requires unnecessary type checkingΒ #42473

Closed
@ChocolateLoverRaj

Description

@ChocolateLoverRaj

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions