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.