export type NumberId = OpaqueType<number, 'NumberId'>;
export const numberId = asOpaque<NumberId, number>;
export type MarkdownString = OpaqueType<string, 'MarkdownString'>;
export const markdownString = asOpaque<MarkdownString, string>;
interface Post {
id: NumberId;
title: string;
body: MarkdownString;
}
declare function findPost(id: NumberId): Post | null;
function handleAPICall(params: {postId: number}) {
const postId = numberId(params.postId);
return findPost(postId);
}
A way to improve type-safety by ensuring values with generic types (like primitives) have a meaningfull type name related to business logic.
To avoid type casting across a project, each declared OpaqueType should have a sibling method to cast
Tto the declared OpaqueType.buildAsOpaqueis a typesafe helper to generate this casting method.Bonus point, It becomes easy to locate the boundaries between the outside and the inside of a domain by searching the usage of this method.