Last active
May 10, 2020 15:25
-
-
Save RobYed/c3e8aaf9ca392e5167191a1e5024874c to your computer and use it in GitHub Desktop.
TypeScript interface for type checking IDs at compile time only. No need to convert id values at runtime.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This interface forces typescript to differentiate between | |
* two IDs which use a different generic type. | |
*/ | |
export interface Id<T> extends String { | |
__idTypeFor?: T; | |
} | |
// syntactic sugar for importing the specific ID type | |
export type PersonId = Id<Person>; | |
export interface Person { | |
id: PersonId; | |
address: Address; | |
} | |
// syntactic sugar for importing the specific ID type | |
export type AddressId = Id<Address>; | |
export interface Address { | |
id: AddressId; | |
} | |
const a: Address = { id: 'some-address-id' }; | |
const p: Person = { id: 'some-person-id', address: a }; | |
// assign AddressId to PersonId | |
p.id = a.id; // TS: Type 'AddressId' is not assignable to type 'PersonId'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This obviously doesn't work for types which share the same shape.