Branding은 타입스크립트 고유 문법이 아닌 응용입니다. 브랜딩을 위해서는 먼저 다음과 같은 코드가 필요합니다.
type Brand<T, B extends string> =
T & { readonly __brand: B };
위의 타입 정의를 통해 string 타입이지만 다른 용도로 정의할 수 있습니다. (브랜딩 화)
type UserId = Brand<string, "UserId">; type PostId = Brand<string, "PostId">;
즉 UserId와 PostId는 string 타입이지만 이 둘은 서로 다른 타입입니다. 만약 다음과 같은 함수가 있다면..
function getPost(userId: UserId, postId: PostId) {
// ...
}
위의 함수는 반드시 다음처럼 사용해야 합니다.
const userId = "hjkim" as UserId; const postId = "3434" as PostId; getPost(userId, postId); // ✅ // getPost(postId, userId); // ❌
