前置知识: TypeScript

符号与唯一类型

1 minIntermediate2026/6/14

Symbol与unique symbol

1. Symbol

const sym: symbol = Symbol('description');

// unique symbol — 每个都是唯一的
const key1: unique symbol = Symbol('key');
const key2: unique symbol = Symbol('key');

type T1 = typeof key1; // unique symbol
type T2 = typeof key2; // unique symbol
// T1 和 T2 不兼容

2. Symbol 作为属性键

const nameKey: unique symbol = Symbol('name');

interface Person {
  [nameKey]: string;
  age: number;
}

const person: Person = {
  [nameKey]: 'Alice',
  age: 25,
};

console.log(person[nameKey]); // 'Alice'

3. 内置 Symbol

interface Iterable<T> {
  [Symbol.iterator](): Iterator<T>;
}

interface IteratorResult<T> {
  value: T;
  done: boolean;
}

// Symbol.hasInstance
class MyArray {
  static [Symbol.hasInstance](instance: unknown) {
    return Array.isArray(instance);
  }
}

// Symbol.toPrimitive
class Money {
  constructor(private amount: number) {}
  [Symbol.toPrimitive](hint: string) {
    if (hint === 'string') return `$${this.amount}`;
    return this.amount;
  }
}

4. well-known Symbol

typeof Symbol.iterator; // unique symbol
typeof Symbol.hasInstance; // unique symbol
typeof Symbol.toPrimitive; // unique symbol
typeof Symbol.toStringTag; // unique symbol