Dynamic key

2 snippets across 2 stacks - JavaScript, TypeScript

Also written as dynamic keys

JSJavaScript

Property Shorthand and Computed Keys

JS · Objects
Syntax
const obj = { name, [expression]: value };
Example
const name = "Mira";
const role = "admin";
const user = { name, role };
console.log(user); // { name: "Mira", role: "admin" }

const field = "email";
const form = { [field]: "[email protected]" };
console.log(form); // { email: "[email protected]" }

Note Shorthand works when the variable name matches the desired key name. Computed keys are evaluated at runtime.

TSTypeScript

Index Signatures

TS · Interfaces
Syntax
interface Name {
  [key: string]: Type;
  [index: number]: Type;
}
Example
interface TranslationMap {
  [locale: string]: string;
}

const greetings: TranslationMap = {
  en: "Hello",
  es: "Hola",
  ja: "こんにちは",
};

// Mixed: known + dynamic keys
interface AppConfig {
  appName: string;
  version: string;
  [key: string]: string; // all values must be string
}
Output
// greetings["fr"] is string (even if missing at runtime)

Note Index signatures allow any key of the given type. When combined with named properties, all named property types must be compatible with the index signature type. Enable noUncheckedIndexedAccess in tsconfig to get T | undefined instead of just T for indexed access - much safer.

Frequently asked questions

How does JavaScript handle dynamic key?
This task is covered in 2 stacks on this page: JavaScript, TypeScript. The "Property Shorthand and Computed Keys" snippet in JavaScript uses `const obj = { name, [expression]: value };`.
Which code does the JavaScript example use?
The "Property Shorthand and Computed Keys" snippet uses `const obj = { name, [expression]: value };`, from the Objects section of the JavaScript cheat sheet.
Which stacks cover "dynamic key" on this page?
JavaScript, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Property Shorthand and Computed Keys": Shorthand works when the variable name matches the desired key name. Computed keys are evaluated at runtime.