Last active
June 8, 2023 12:31
-
-
Save mmyoji/d593a25ac7be6bee9664ccc01cdf166d to your computer and use it in GitHub Desktop.
Nominal Types in TS
This file contains hidden or 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
// 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