Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to type check String Aliases in TypeScript?

Tags:

typescript

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?

like image 827
corgrath Avatar asked Dec 10 '22 05:12

corgrath


1 Answers

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

like image 172
Titian Cernicova-Dragomir Avatar answered Jun 08 '23 07:06

Titian Cernicova-Dragomir