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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With