Search code examples
typescripttsc

How to prevent mixture of custom string types?


Suppose we have two custom types, both derived from string, and two corresponding variables.

type A = string;
let a: A = "a";

type B = string;
let b: B = "b";

How can the code or the compiler configuration be changed, so that the following will raise a type mismatch error?

a = b;

Solution

  • Typescript has a structural type system, not a nominal type system. In practical terms, this means that it is the shape of things that matter, not what you happen to name them. So it is not possible to restrict things given your example.

    If A and B can only be assigned from a set of known strings at compile time, it is possible to represent them more accurately.

    Eg:

    type A = 'one' | 'two';

    type B = 'three' | 'four';

    These types cannot be assigned to one another