Skip to content

number & { __brand } is not working with the comparison operator in nightly build #11643

Closed

Description

declare var x: number & { __brand: any };
x > 0 // <-- [ts] Operator '>' cannot be applied to types 'number & { __brand: any; }' and '0'.

Activity

  1. aozgaa commented on Oct 17, 2016

    @aozgaa
    Contributor

    The error first appeared in a63a0d8.

  2. aozgaa commented on Oct 19, 2016

    @aozgaa
    Contributor

    Hey Aleksey,

    This ties into an ongoing discussion about what we think about the use/addition of nominal types in our type system. There is a long list of issues related to nominal types.

    It looks like this feature is actually working as designed, though the behavior is admittedly a bit counter-intuitive at first glance. Based on the recent addition of the comparability relation (issue #5517), specifically here, x isn't comparable to '0' because '0' is a numeric literal, and thus a subtype of 'number'. Here are two workarounds (inspired by your comment here :) ):

    type BrandedNum = number & { __numberBrand: any };
    
    declare var x : BrandedNum;
    x > 0; // error: 0 is of numeric literal '0', a subtype of number
    x > <number>0; // okay
    x > <BrandedNum>0; // okay, in my opinion the clearest
    

    In fact, this should be a general solution for dealing with "nominal typing" via brands: upcasting the other argument to a comparison operation to that of the two types' common ancestor will make the comparison pass our type check.

  3. added
    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead
    Design LimitationConstraints of the existing architecture prevent this from being fixed
    on Oct 19, 2016
  4. zpdDG4gta8XKpMCd commented on Oct 19, 2016

    @zpdDG4gta8XKpMCd
    Author

    interesting, i will consider that

  5. removed
    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead
    on Oct 19, 2016
  6. locked and limited conversation to collaborators on Jun 19, 2018
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 LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions