TypeScript example

How to create a dictionary in TypeScript

9 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Type a plain object as Record<string, T>: const scores: Record<string, number> = {};, then add entries with scores["ada"] = 92. A bare {} without a type has no properties, so adding one fails with Property 'port' does not exist on type '{}'. Use Map<K, V> instead when keys aren't strings, when you add and delete a lot, or when keys come from user input.

TypeScript has no separate dictionary type. A dictionary is either a plain object whose type says "any string key, values of type T" (Record<string, T> or the index signature { [key: string]: T }, which mean the same thing), or a Map, the JavaScript class closest to C#'s Dictionary. The choice changes what the checker allows: which keys you may add, whether a lookup can be missing, and whether every key of a union has to be present. Each example runs on this page: hit Run, then edit the code and run it again.

1Record<string, T>: an object used as a dictionaryRecommended

Record<string, number> says: any string key, and every value is a number. Once the variable has that type you can add, update and delete keys freely, with brackets for a key in a variable and with a dot for a fixed name. The checker still guards the values, so scores.ada = "high" is an error. Check for a key with Object.hasOwn rather than in, which also finds keys every object inherits, such as toString.

record.ts
// A dictionary from string keys to numbers
const scores: Record<string, number> = {
    ada: 92,
    grace: 88,
};

// Add and update entries with brackets or a dot
scores["linus"] = 75;
scores.ada = 95;

const name = "grace";
console.log(scores[name]);
console.log(scores);

// Check for a key with Object.hasOwn: "in" also sees inherited keys
console.log(Object.hasOwn(scores, "linus"), Object.hasOwn(scores, "bob"));
console.log("toString" in scores, Object.hasOwn(scores, "toString"));

// A missing key reads as undefined, though the type says number
console.log(scores["bob"]);
console.log(scores["bob"] ?? 0);

// Remove an entry and count what is left
delete scores.linus;
console.log(Object.keys(scores).length, JSON.stringify(scores));

// Build one up from data
function countLetters(word: string): Record<string, number> {
    const counts: Record<string, number> = {};
    for (const ch of word) {
        counts[ch] = (counts[ch] ?? 0) + 1;
    }
    return counts;
}
console.log(countLetters("banana"));

Output

The lookup prints 88 and the whole dictionary prints { ada: 95, grace: 88, linus: 75 }. Object.hasOwn gives true false for linus and bob, while the next line, true false, shows in reporting a toString key that was never added. A missing key reads as undefined, and ?? 0 turns that into 0. Note that the type of scores["bob"] is number, not number | undefined, even with strict on: TypeScript assumes every key of a Record exists unless you also turn on noUncheckedIndexedAccess. After the delete two keys remain, {"ada":95,"grace":88}, and countLetters("banana") builds { b: 1, a: 3, n: 2 } one key at a time.

2Adding properties to {}: "Property does not exist on type '{}'"

The most common way to hit this topic is from the other side: you write const config = {} and add properties later, the way JavaScript allows. TypeScript infers the type of a variable from its first value, and the type of an empty object literal is {}, an object with no known properties. Assigning a new property by name is then an error, and because a type error stops the program, nothing runs.

empty-object.ts
// An empty object literal gets the type {}: an object with no properties
const config = {};
config.port = 8080;
config.host = "localhost";

console.log(config);

Output

The checker stops with error TS2339: Property 'port' does not exist on type '{}'. and the same error for host. An object that starts with some properties fails the same way: const user = { name: "Ada" } followed by user.age = 36 gives error TS2339: Property 'age' does not exist on type '{ name: string; }'. Give the variable a type up front instead. If the keys are open-ended, that is Record<string, T> (section 1). If you know the property names, declare them, with ? on the ones added later (section 3). {} as ServerConfig also silences the error, but it promises the checker the required properties are there without checking. With strict off, as on this page, a bracket assignment such as dict[key] = 8080 on a {} compiles and runs; with strict on, as in most projects, it is error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. The fix is the same: type the object.

3Index signatures: interfaces with dynamic keys

An index signature, [name: string]: string, is the form of Record you can put inside an interface. On its own it means exactly what Record<string, string> means; the name before the colon only documents the key. Its real use is mixing known properties with extra keys, as in a table row that always has an id and a name plus any number of other columns. The rule: every known property must also fit the index type, so the index type is usually a union. When you do know the names, prefer optional properties to an index signature.

index-signature.ts
// An index signature: any string key, string values
interface EnvVars {
    [name: string]: string;
}
const env: EnvVars = { NODE_ENV: "production" };
env.LOG_LEVEL = "debug";
env["APP_PORT"] = "8080";
console.log(env);

// Known properties plus extra keys: each known one must fit the index type
interface ProductRow {
    id: number;
    name: string;
    [column: string]: string | number;
}
const row: ProductRow = { id: 7, name: "Lamp" };
row.color = "teal";
row.weightKg = 1.2;
console.log(row.name.toUpperCase(), row.id + 1, row);

// Known keys that arrive later: optional properties, not an index signature
interface ServerConfig {
    host: string;
    port?: number;
    tls?: boolean;
}
const config: ServerConfig = { host: "localhost" };
config.port = 8080;
console.log(config);

// Number keys are checked as numbers but stored as strings
const byId: { [id: number]: string } = { 1: "Ada", 2: "Grace" };
byId[3] = "Linus";
console.log(byId[2], Object.keys(byId));

// A template literal key type limits which names are allowed
const attrs: { [key: `data-${string}`]: string } = {};
attrs["data-role"] = "button";
attrs["data-state"] = "open";
console.log(attrs);

Output

env accepts new keys by dot and by bracket and prints all three. The row keeps its precise types for the known properties, so row.name.toUpperCase() and row.id + 1 work and the line prints LAMP 8 before the row itself. Make the index type plain string while id is a number and the checker rejects the interface: error TS2411: Property 'id' of type 'number' is not assignable to 'string' index type 'string'. The number-keyed object prints Grace [ '1', '2', '3' ]: object keys are always strings at runtime, whatever the type says. The template literal key type takes data-role and data-state; a literal such as { title: "x" } is rejected with error TS2353: Object literal may only specify known properties, and 'title' does not exist in type '{ [key: `data-${string}`]: string; }'.

4Record with a union of keys: every key required

Record earns its name when the key type is a union of string literals. Record<Status, string> is an object with exactly the keys todo, doing and done, all required. That makes it the right type for lookup tables such as labels, colours or handlers per case: add a member to Status and every table that forgot it stops compiling. When only some keys are present, wrap it in Partial. To build the union from an array or an object you already have, see how to create a union type from an array.

record-union.ts
type Status = "todo" | "doing" | "done";

// Record with a union of keys: every key must be there
const labels: Record<Status, string> = {
    todo: "To do",
    doing: "In progress",
    done: "Done",
};

interface Task {
    title: string;
    status: Status;
}
const tasks: Task[] = [
    { title: "Write spec", status: "done" },
    { title: "Build API", status: "doing" },
    { title: "Ship it", status: "todo" },
    { title: "Fix login bug", status: "done" },
];

// Every count starts at zero, so each key exists before the loop
const counts: Record<Status, number> = { todo: 0, doing: 0, done: 0 };
for (const task of tasks) {
    counts[task.status] += 1;
}

const order: Status[] = ["todo", "doing", "done"];
for (const status of order) {
    console.log(`${labels[status]}: ${counts[status]}`);
}

// Partial<Record<...>> when only some keys are present
const owners: Partial<Record<Status, string>> = { doing: "Ada" };
owners.done = "Grace";
for (const status of order) {
    console.log(`${status} -> ${owners[status] ?? "nobody"}`);
}

Output

The counts print To do: 1, In progress: 1 and Done: 2. counts[task.status] += 1 is safe because the type guarantees each key exists, which is why the object starts with all three at zero. Leave done out of labels and the checker reports error TS2741: Property 'done' is missing in type '{ todo: string; doing: string; }' but required in type 'Record<Status, string>'. Misspell it as dne and you get TS2561, which ends Did you mean to write 'done'? The Partial table prints todo -> nobody, doing -> Ada and done -> Grace. There each value is string | undefined, so with strict on, owners.done.toUpperCase() fails with error TS18048: 'owners.done' is possibly 'undefined'. until you check it or give a default with ??.

5Map<K, V>: a real dictionary class

Map<K, V> is the closest thing to C#'s Dictionary or a Java HashMap. Keys can be any type and keep it, entries come back in insertion order, size is a property, and there are no inherited keys to trip over. Its get is typed V | undefined, so the checker makes you handle a missing key. Use it when keys are not strings, when keys come from user input, or when the collection grows and shrinks a lot.

map.ts
// Map: any key type, a size, and insertion order
const stock = new Map<string, number>([
    ["apples", 12],
    ["pears", 0],
]);
stock.set("plums", 30);
stock.set("apples", 10);       // set on an existing key updates it

console.log(stock.size, stock.has("pears"), stock.has("kiwis"));

// get returns number | undefined: check before you use it
const plums = stock.get("plums");
if (plums !== undefined) {
    console.log(plums.toFixed(2));
}
console.log(stock.get("kiwis"), stock.get("kiwis") ?? 0);

stock.delete("pears");
for (const [fruit, qty] of stock) {
    console.log(`${fruit}: ${qty}`);
}

// Keys keep their type: numbers stay numbers
const names = new Map<number, string>([[1, "Ada"], [2, "Grace"]]);
console.log([...names.keys()], names.get(2));

// A plain object inherits keys such as "constructor"; a Map starts empty
function countWithRecord(words: string[]): Record<string, number> {
    const counts: Record<string, number> = {};
    for (const w of words) counts[w] = (counts[w] ?? 0) + 1;
    return counts;
}
function countWithMap(words: string[]): Map<string, number> {
    const counts = new Map<string, number>();
    for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
    return counts;
}
const words = ["the", "constructor", "the"];
console.log(countWithRecord(words));
console.log(countWithMap(words));

Output

3 true false is the size and two has checks, the checked get prints 30.00, and a missing key gives undefined 0. With strict on, stock.get("plums").toFixed(2) without the check is error TS2532: Object is possibly 'undefined'., and wrapping it in if (stock.has("plums")) does not help, because has doesn't narrow a later get: store the result and compare it with undefined. The number keys stay numbers, [ 1, 2 ]. The last two lines are the reason to prefer a Map for keys you don't control: counting the word constructor in a plain object starts from the inherited Object function and stores 'function Object() { [native code] }1', while the Map prints Map(2) { 'the' => 2, 'constructor' => 1 }. Never write stock["kiwis"] = 5 on a Map: on this page it compiles and sets a plain property, so size stays 0 and get returns undefined. With strict on it is caught: error TS7052: Element implicitly has an 'any' type because type 'Map<string, number>' has no index signature. Did you mean to call 'stock.set'?

6Key-value pairs, and converting between Record and Map

A single key-value pair is a tuple: [string, number], or with labels [name: string, score: number], which only change the editor hints. Object.entries turns a Record into an array of those pairs, Object.fromEntries turns pairs (or a Map) back into an object, and new Map(Object.entries(obj)) goes the other way. For walking over a dictionary, and why Object.keys returns string[], see how to loop through an object.

pairs.ts
// One key-value pair: a tuple type, with labels for readability
type ScorePair = [name: string, score: number];
const pair: ScorePair = ["ada", 92];
const [name, score] = pair;
console.log(name, score);

// Object.entries turns a dictionary into an array of pairs
const scores: Record<string, number> = { ada: 92, grace: 88, linus: 75 };
const entries: [string, number][] = Object.entries(scores);
console.log(entries);

// Object.fromEntries turns pairs back into an object
const curved = Object.fromEntries(entries.map(([k, v]) => [k, v + 5]));
console.log(curved);

// Record to Map and back
const map = new Map(Object.entries(scores));
map.set("bob", 60);
const back: Record<string, number> = Object.fromEntries(map);
console.log(back);

// JSON.stringify skips a Map's entries: convert it first
console.log(JSON.stringify(map));
console.log(JSON.stringify(Object.fromEntries(map)));

Output

The pair destructures to ada 92, and Object.entries prints [ [ 'ada', 92 ], [ 'grace', 88 ], [ 'linus', 75 ] ], typed [string, number][]. Mapping the pairs and calling Object.fromEntries gives { ada: 97, grace: 93, linus: 80 }, and the round trip through a Map keeps the added bob: 60. The last two lines matter for APIs: JSON.stringify of a Map is {}, because its entries are not properties. Convert with Object.fromEntries first to get {"ada":92,"grace":88,"linus":75,"bob":60}.

7Which should you use?

TypeKeysMissing keyBest for
Record<string, T>StringsTyped as T (assumed present)The default: JSON-shaped lookups and counters
{ [key: string]: T }StringsTyped as T (assumed present)Interfaces mixing known props with extra keys
Record<Union, T>Exactly the union, all requiredCannot happenLookup tables per case: labels, handlers
Partial<Record<Union, T>>Only the union, any subsetT | undefinedSome keys of a known set
Map<K, V>Any type, kept as isV | undefined from get()Non-string or untrusted keys, frequent add/delete
[K, V] tuplesAny, duplicates allowedSearch with find()Ordered pair lists, Object.entries output

Frequently asked questions

What is the Record type in TypeScript?

Record<K, V> is a built-in utility type for an object whose keys are of type K and whose values are of type V. With K = string it is a dictionary: Record<string, number> is the same type as { [key: string]: number }. With a union such as Record<"todo" | "done", string> it is an object with exactly those keys, all required. It exists only at compile time; at runtime the value is a plain object.

What is the difference between Record<string, T> and an index signature?

For string keys there is none: Record<string, T> and { [key: string]: T } describe the same type, and most code uses Record because it is shorter. An index signature can sit inside an interface next to known properties (each must fit the index type), while Record can take a union of literal keys, which an index signature cannot. Pick Record for a standalone dictionary and an index signature for an interface with extra keys.

Should I use a Map or an object as a dictionary in TypeScript?

Use a Record object when the keys are strings you control and the data goes to or from JSON. Use a Map when keys are numbers, objects or user input, when you add and delete often, or when you want get to be typed V | undefined. A plain object inherits keys such as constructor and toString, so counting arbitrary words in one gives wrong results; a Map has no such keys. Remember that JSON.stringify(map) is {}: convert with Object.fromEntries(map) first.

Why is dict[key] not typed as possibly undefined?

TypeScript assumes every key of a Record<string, T> or index signature exists, so scores["bob"] is typed number even when the key is missing and the value is undefined. Turn on noUncheckedIndexedAccess in tsconfig to make every index read T | undefined, or check with Object.hasOwn(dict, key) or dict[key] ?? fallback. A Map does this by default: map.get(key) returns V | undefined.

How do I make a Record with optional keys?

Wrap it in Partial: Partial<Record<Status, string>> allows any subset of the keys, and each value is typed string | undefined. A plain Record<Status, string> requires every key, and leaving one out is error TS2741. See the omit-a-property-from-a-type example for Partial, Pick and Omit.

How do I declare a key-value pair type in TypeScript?

Use a tuple: type Pair = [string, number], or [name: string, score: number] with labels. That is the shape Object.entries returns and new Map() and Object.fromEntries accept. If you prefer named fields, use an interface such as { key: string; value: number } and keep the pairs in an array.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground