← 中文资源

简体中文版本

unique symbol 名义键

用 unique symbol 声明名义键:对象品牌无法用普通字符串伪造,只有持有该符号的模块才能铸造出合法值,类型与运行时边界同时收紧。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

id: u_ab12cd | length: 8
lookup: ada
hello u_ab12cd

实现说明

函数 toUserId、greet是实现的聚合点。 TypeError 在其所在位置无条件抛出——前面没有任何输入检查。

使用要点

  • 直接运行文件,输出会带上标签,比如 id:、lookup:——输出的每一行都能指回产生它的那次调用。

常见问题

这里有输入检查吗?

没有输入检查:TypeError 在执行到达那一行就会触发,与任何数据形态无关。

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 toUserId、greet。

主签名形如 function toUserId(raw: string)

核心语句

throw new TypeError('invalid user id: ' + raw);
return 'hello ' + who;

代码示例

// 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));