TypeScript Reference ยท Type Operators
TypeScript computed property keys
Reference for TypeScript computed property keys: [expr] in objects, classes and types, unique symbol keys, literal-typed keys and the rules for each.
A computed property key puts an expression in square brackets where a property name would go: { [key]: value }. TypeScript can follow the key into the type system only when the expression has a literal type or is a unique symbol. With a plain string key the property becomes an index signature instead.
Symbols are the most useful case. A const declared with Symbol() gets the type unique symbol, and using it as a key creates a property that no string can collide with.
const id = Symbol("id"); const user = { [id]: 1, name: "Ann" }; // type: { [id]: number; name: string }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
{ [expression]: value }
interface I { [literalOrSymbol]: Type }
class C { [key]: Type; [key]() {} }
type M = { [K in Keys]: Type } // mapped type, a different feature
| Key expression | Resulting type member |
|---|---|
String or number literal type ("a", 1) |
A normal named property. |
unique symbol (a const or static readonly initialized by Symbol()) |
A property keyed by that symbol. |
string or number (wide) |
An index signature. |
| Union of literals | In type positions, an error; use a mapped type. |
Errors: in an interface, class or type literal the key must be of a literal or unique symbol type, otherwise error 1169, "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type".
Usage notes
unique symbolneedsconst(orstatic readonly).let s = Symbol()is justsymbol. The type is tied to the declaration, so two separateSymbol("x")constants are different types.- Well-known symbols such as
Symbol.iteratorandSymbol.toPrimitiveare keys declared in the standard library, which is how[Symbol.iterator]()makes a class iterable. Symbol.for(key)is not unique. It returns the same global symbol each time, and its type is plainsymbol.- Symbols are hidden from
Object.keys,for...inandJSON.stringify, useful for metadata, but visible throughObject.getOwnPropertySymbols. - Order is by insertion for strings, with integer-like keys first; symbols come after.
- Duplicates: computed keys evaluated at runtime can overwrite earlier properties silently.
- Exporting symbols: declare them in one module and import by name; the unique type follows the import.