Skip to content

Commit

Permalink
Add branded strings
Browse files Browse the repository at this point in the history
  • Loading branch information
schani committed Apr 10, 2024
1 parent ccc2bab commit 60e9403
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/branded-strings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* A branded string is a string that has a unique type, so that it can be
* distinguished from other strings. This is useful when you want to ensure
* that a string is only used in a specific context. When assigning to a
* branded string type it's not allowed to assign a non-branded string, or a
* string of the wrong brand:
*
* ```ts
* type Apple = BrandedString<"apple">;
* type Orange = BrandedString<"orange">;
*
* const apple: Apple = brandString("Pink Lady");
* let orange: Orange = apple; // error!
* orange = "jalapeño"; // error!
* let justAString: string = apple; // This is ok
*/
export type BrandedString<T extends string> = string & { __brand: T };

/**
* Brands a string with the specified brand.
*
* @param s The string to brand.
*/
export function brandString<T extends string>(s: string): BrandedString<T> {
return s as BrandedString<T>;
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,5 @@ export function exceptionToError(e: unknown): Error {
}

export { DefaultMap, ReadonlyDefaultMap } from "./default-map";

export { BrandedString, brandString } from "./branded-strings";

0 comments on commit 60e9403

Please sign in to comment.