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.

TypescriptSecurity Boundaries

Code

typescriptsnippet
26 lines
// 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_ab12cd

Under 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

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.