Skip to content

Commit

Permalink
New function makeBrandString
Browse files Browse the repository at this point in the history
  • Loading branch information
schani committed Apr 12, 2024
1 parent 60e9403 commit d5d5a44
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@glideapps/ts-necessities",
"version": "2.2.0",
"version": "2.2.1",
"description": "Small utilities to make life with TypeScript easier",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
17 changes: 17 additions & 0 deletions src/branded-strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* 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 };

Expand All @@ -24,3 +25,19 @@ export type BrandedString<T extends string> = string & { __brand: T };
export function brandString<T extends string>(s: string): BrandedString<T> {
return s as BrandedString<T>;
}

/**
* Returns a function that brands a string with the specified brand. For
* example:
*
* ```ts
* type Apple = BrandedString<"apple">;
* // `makeApple` will be of type `(s: string) => Apple`
* const makeApple = makeBrandString<Apple>();
* // `apple` will be of type `Apple`
* const apple = makeApple("Pink Lady");
* ```
*/
export function makeBrandString<T>(): T extends BrandedString<any> ? (s: string) => T : never {
return brandString as any;
}
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,4 @@ export function exceptionToError(e: unknown): Error {

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

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

0 comments on commit d5d5a44

Please sign in to comment.