5

Given this code:

type Firstname = string
type Surname  = string

const firstname: Firstname = "John";
const surname:Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

/*
 * This should give a compile error
 */

print(surname);

Is it possible to disallow passing in a Surname when the function requires a Firstname?

corgrath
  • 11,673
  • 15
  • 68
  • 99
  • 1
    Nominal typing is something TypeScript have on their roadmap. See https://github.com/Microsoft/TypeScript/wiki/Roadmap and https://github.com/Microsoft/TypeScript/issues/202 – Brendan Annable Jul 29 '18 at 11:08

1 Answers1

17

You are looking for what is called branded types. In typescript type compatibility is decided structurally so the alias will not make types incompatible but we can make them structurally different using an intersection type and a unique symbol:

type Firstname = string & { readonly brand?: unique symbol }
type Surname = string & { readonly brand?: unique symbol }

const firstname: Firstname = "John"; // we can assign a string because brans is optional 
const surname: Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

print(surname); // error unques symbol declarations are incompatible 

Different variations on this may be useful but the basic idea is the same, you might find these similar answers useful : guid definition, index and position , and others

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357