TypeScript Branded型

TypeScriptでは以下のように型が一致している場合にはエラーにはならない。

type Name = string
type Id = string

const myName: Name = 'tamibouz';
const myId: Id = myName; 
//どちらもstringなのでId型にName型を間違っていれてもエラーにならない(本当はエラーにしたい)

実際には使用しないプロパティを追加して二つの型に差を持たせることで、それぞれ違う型として使うことができる。(Branded型)

type Brand<K,T> = K & {_brand: T}

type Name = Brand<string, 'Name'>
// type Name = string & {
//     _brand: "Name";
// }
type Id = Brand<string, 'Id'>
// type Id = string & {
//     _brand: "Id";
// }

const createName = (name: string) => {
    return name as Name
};
const createId = (id: string) => {
    return id as Id
};

const myName: Name = createName('tamibouz');
const myId: Id = myName; //型エラー