Codectionary / Developer documentation / TypeScript

Unique Symbols as Property Keys

A unique symbol type identifies one particular symbol declaration.

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.js

Syntax

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(","));
  1. The computed property uses the symbol itself as its key.
  2. The bracket lookup retrieves 7 using that exact symbol.
  3. Object.keys lists enumerable string keys, so it shows name only. Symbol properties can still be inspected with symbol-aware reflection APIs.
  4. 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

Specifications & further reading