Unique Symbols For Nominal Keys
Declare unique symbol keys so object brands cannot be forged with plain strings and only the owning module can mint valid values.
Code
// unique symbol:只有持有该符号的模块才能铸造合法值
declare const userIdBrand: unique symbol;
type UserId = string & { readonly [userIdBrand]: true };
function toUserId(raw: string): UserId {
if (!/^u_[a-z0-9]{6}$/.test(raw)) {
throw new TypeError('invalid user id: ' + raw);
}
return raw as UserId;
}
const id = toUserId('u_ab12cd');
console.log('id:', id, '| length:', id.length);
// 普通字符串不能直接赋给 UserId,必须经过构造函数
// const forged: UserId = 'u_zzzzzz';
const table: Record<UserId, string> = { [id]: 'ada' };
console.log('lookup:', table[id]);
function greet(who: UserId): string {
return 'hello ' + who;
}
console.log(greet(id));Output
Captured from a sandboxed run of this snippet in the build pipeline.
id: u_ab12cd | length: 8
lookup: ada
hello u_ab12cdUnder the hood
Unique Symbols For Nominal Keys keeps everything in the functions toUserId and greet.
A TypeError is thrown unconditionally at its throw site — no input check sits in front of it.
Using it
Signature: function toUserId(raw: string)
Running the file prints labeled results such as id:, lookup: — each operation’s effect is visible in the output.
Key statements
throw new TypeError('invalid user id: ' + raw);
return 'hello ' + who;
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Is there any input checking?
- No input check exists: the `TypeError` fires whenever execution reaches its line, not in response to any data shape.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `toUserId`, `greet` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.