Skip to content

How to make more better structural branded types #8510

Description

@falsandtru

It can create lots of new types easily and structurally.

function build<N, T>() {
  return <{
    (a: N & T): void;
    (a: T): N & T;
  }>((a: T) => a);
}

namespace Types {
  export namespace Nominal1 {
    class Nominal<T> {
      private NOMINAL: T;
    }
    export type A = Nominal<'A'> & number;
    export const A = build<Nominal<'A'>, number>();
    export type B = Nominal<'B'> & number;
    export const B = build<Nominal<'B'>, number>();
  }
}

namespace Types {
  export namespace Nominal2 {
    class Nominal<T> {
      private NOMINAL: T;
    }
    export type A = Nominal<'A'> & number;
    export const A = build<Nominal<'A'>, number>();
    export type B = Nominal<'B'> & number;
    export const B = build<Nominal<'B'>, number>();
  }
}

var a1: Types.Nominal1.A;
var b1: Types.Nominal1.B;
var a2: Types.Nominal2.A;
a1 = b1; // error
a1 = a2; // error
a1 = Types.Nominal1.A(0); // ok
a1 = Types.Nominal1.A(a1); // error
a1 = Types.Nominal1.B(0); // error
a1 = Types.Nominal2.A(0); // error

Activity

  1. mhegazy commented on May 7, 2016

    @mhegazy
    Contributor

    looks like the same topic as in #4895. i suggest moving the discussion there.

  2. falsandtru commented on May 8, 2016

    @falsandtru
    ContributorAuthor

    This issue posted only for documentation. This is a different technique, and has a different purpose from #4895.

  3. mhegazy commented on May 20, 2016

    @mhegazy
    Contributor

    This issue posted only for documentation. This is a different technique, and has a different purpose from #4895.

    I understand; #4895 is a discussion item that is meant for brainstorming and sharing ideas.

  4. 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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions