Skip to content

Failure to refine generic argument of type extends boolean #41333

Closed

Description

@0rvar

TypeScript Version: 4.0, nightly

Search Terms:
Generic, refinement, refine, extends boolean

Code

function foo<TValue extends boolean>(value: TValue) {
  if (value === true) {
    const truthy: true = value
  }
}

Expected behavior:
TValue should be refined to true. At the very least, the value variable should.

Actual behavior:
Error:

Type 'TValue' is not assignable to type 'true'.
  Type 'boolean' is not assignable to type 'true'.(2322)

Playground Link:
https://www.typescriptlang.org/play?ts=4.1.0-dev.20201030#code/GYVwdgxgLglg9mABMOcA8AVAagQwDYgCmihAHlIWACYDOiARqnoTmAHwAUAbvkQFyJsvQgEpEAbwCwAKESIYwRN2GIAvOsRQATkTFTZcxBAQ0omnVAAWATwHaiaxDwKEZcgL4zP0oA

Activity

  1. added
    Working as Intended
    Design Limitation
    and removed
    Working as Intended
    on Nov 10, 2020
  2. RyanCavanaugh commented on Nov 10, 2020

    @RyanCavanaugh
    Member

    Narrowing doesn't quite work this way and it'd be difficult to make it do this without breaking other behavior. Ideally it'd be something like TValue & true but that kind of analysis only makes sense on unit values like true and false, but it's rarely useful to write generics that operate like that.

  3. 0rvar commented on Nov 11, 2020

    @0rvar
    Author

    Narrowing doesn't quite work this way and it'd be difficult to make it do this without breaking other behavior.

    Could you elaborate?

    it's rarely useful to write generics that operate like that.

    Here's a slightly contrived use case:

    type FullPayload = { _brand: 1 };
    type LightPayload = { _brand: 2 };
    type PayloadTypes = 'full' | 'light';
    function callApi<TType extends PayloadTypes>(type: TType, payload: TType extends 'full' ? FullPayload : LightPayload) {
      if (type === 'full') {
        const fullPayload: FullPayload = payload; // Type error
        // serialization logic for full payload etc
      }
      // else etc
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design Limitation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions