Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Branding 技巧:在类型层面“打标签” #684

Open
981377660LMT opened this issue Jan 2, 2025 · 1 comment
Open

Branding 技巧:在类型层面“打标签” #684

981377660LMT opened this issue Jan 2, 2025 · 1 comment

Comments

@981377660LMT
Copy link
Owner

No description provided.

@981377660LMT
Copy link
Owner Author

在某些业务场景里我们希望区分“相同结构但不同含义”的数据,通常可以用“品牌化” (Branding) 来让编译器识别它们是完全不同的类型。最简单的方法是加个不存在的“tag”或“_brand”字段:

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

type UserId = Brand<'UserId', number>;
type OrderId = Brand<'OrderId', number>;

function getUserById(id: UserId) { /* ... */ }

const uid = 123 as UserId;
const oid = 123 as OrderId;

getUserById(uid);  // OK
getUserById(oid);  // Error:即使结构相同也不能乱用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant