What it is and why to use it
A unique symbol type identifies one particular symbol declaration. Symbols are runtime primitive keys, and two newly created symbols differ even if their descriptions are identical. This is useful for library metadata that should avoid colliding with ordinary string-named properties.
Common mistakes and limitations
A symbol key is not a secret or access-control mechanism. Recreating Symbol("identity") creates a different key. Keep the original symbol available to code that needs to access the property.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
const identity: unique symbol = Symbol("identity");Examples
Unique Symbols as Property Keys
Standalone TypeScript 5.8+ example; expected output is explained below.
const identity: unique symbol = Symbol("identity");
type User = { name: string; [identity]: number };
const user: User = { name: "John", [identity]: 7 };
console.log(user[identity]);
console.log(Object.keys(user).join(","));- The computed property uses the symbol itself as its key.
- The bracket lookup retrieves 7 using that exact symbol.
- Object.keys lists enumerable string keys, so it shows name only. Symbol properties can still be inspected with symbol-aware reflection APIs.
- Expected output: 7 name
Best practices
- A symbol key is not a secret or access-control mechanism. Recreating Symbol("identity") creates a different key. Keep the original symbol available to code that needs to access the property.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook