Type alias NewType<N, T>

NewType<N, T>: T & {
    [___s]: N;
}

This type represents a new unique type derived from an existing base type. It defines a mechanism similar to Python's NewType. In TypeScript world it's refered to as 'Type Branding'.

Type Parameters

  • N

    The unique identifier for the new type.

  • T

    The base type of the new type.

Type declaration

  • Internal [___s]: N

    Property __s is not intended for direct access nor modification.

Example

type FooID = NewType<'FooID', string>;
type BarID = NewType<'BarID', string>;

const fooId: FooID = 'foo123' as FooID;
const barId: BarID = 'bar456' as BarID;

// Here's a potential bug:
const buggyFooBar = (foo: string, bar: string) => {};
buggyFooBar('bar456', 'foo123'); // this works but it's an undetected bug.

// Bug mitigation:
const safeFooBar = (foo: FooID, bar: BarID) => {};
safeFooBar('bar456', 'foo123'); // TypeScript error: Argument of type 'string' is not assignable to parameter of type 'FooID'.