Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.62 KB

File metadata and controls

48 lines (35 loc) · 1.62 KB
hide_title true
custom_edit_url
pagination_prev
pagination_next

Home > @rushstack/node-core-library > Brand

Brand type

A "branded type" is a primitive type with a compile-type key that makes it incompatible with other aliases for the primitive type.

Signature:

export type Brand<T, BrandTag extends string> = T & {
    __brand: BrandTag;
};

Remarks

Example usage:

// PhoneNumber is a branded type based on the "string" primitive.
type PhoneNumber = Brand<string, 'PhoneNumber'>;

function createPhoneNumber(input: string): PhoneNumber {
  if (!/\d+(\-\d+)+/.test(input)) {
    throw new Error('Invalid phone number: ' + JSON.stringify(input));
  }
  return input as PhoneNumber;
}

const p1: PhoneNumber = createPhoneNumber('123-456-7890');

// PhoneNumber is a string and can be used as one:
const p2: string = p1;

// But an arbitrary string cannot be implicitly type cast as PhoneNumber.
// ERROR: Type 'string' is not assignable to type 'PhoneNumber'
const p3: PhoneNumber = '123-456-7890';

For more information about this pattern, see this comment explaining the TypeScript compiler's introduction of this pattern, and this article explaining the technique in depth.