Skip to content

Instantly share code, notes, and snippets.

@RobYed
Last active May 10, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobYed/c3e8aaf9ca392e5167191a1e5024874c to your computer and use it in GitHub Desktop.
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 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'.
@RobYed
Copy link
Author

RobYed commented May 5, 2020

This obviously doesn't work for types which share the same shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment