Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active June 8, 2023 12:31
Show Gist options
  • Save mmyoji/d593a25ac7be6bee9664ccc01cdf166d to your computer and use it in GitHub Desktop.
Save mmyoji/d593a25ac7be6bee9664ccc01cdf166d to your computer and use it in GitHub Desktop.
Nominal Types in TS
// https://www.typescriptlang.org/play#example/nominal-typing
type ValidatedInputString = string & { __brand: "User Input Post Validation" };
// https://speakerdeck.com/naoya/typescript-niyoru-graphql-batukuendokai-fa-75b3dab7-90a8-4169-a4dc-d1e7410b9dbd?slide=91
declare const __newtype: unique symbol;
export type newtype<Constructor, Type> = Type & {
readonly [__newtype]: Constructor;
};
export type TagId = newtype<"TagId", string>;
export function TagId(value: string): TagId {
if (validate(value)) {
return value as TagId;
}
throw new Error(`invalid tagId=${value}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment