TypeScript does not have a direct equivalent to Python's list comprehensions or dictionary comprehensions in terms of syntax. However, you can achieve similar functionality using JavaScript's built-in array methods and object manipulation techniques. Here's how you can create a dictionary (object) from a list in TypeScript:
✅ 1. Using Array.prototype.map() and Object.fromEntries()
This is the most concise and idiomatic way in modern JavaScript/TypeScript.
const arr = [1, 2, 3];
// Create an object where keys are the elements and values are their squares
const obj = Object.fromEntries(
arr.map(num => [num, num * num])
);
console.log(obj); // { '1': 1, '2': 4, '3': 9 }
Note: In JavaScript, object keys are always strings. If you want numeric keys, consider using a Map instead.
✅ 2. Using Array.prototype.reduce()
A more traditional approach that works in all environments:
const arr = [1, 2, 3];
const obj = arr.reduce((acc, num) => {
acc[num] = num * num;
return acc;
}, {} as Record<number, number>);
console.log(obj); // { 1: 1, 2: 4, 3: 9 }
The Record<number, number> type annotation ensures the object has numeric keys and values.
✅ 3. Using Map for Flexible Key-Value Pairs
If you need non-string keys (e.g., numbers, objects), use Map instead of a plain object:
const arr = [1, 2, 3];
const map = new Map<number, number>(
arr.map(num => [num, num * num])
);
console.log(map); // Map { 1 => 1, 2 => 4, 3 => 9 }
✅ 4. Custom Loop (for clarity)
If you prefer explicit loops:
const arr = [1, 2, 3];
const obj: Record<number, number> = {};
for (const num of arr) {
obj[num] = num * num;
}
console.log(obj); // { 1: 1, 2: 4, 3: 9 }
🔍 Key Differences from Python
- No direct syntax for comprehensions like
{key: value for ...} in TypeScript.
- Objects in JavaScript/TypeScript have string keys by default.
- Use
Map for non-string keys (e.g., numbers, objects).
Summary
While TypeScript lacks Python-like comprehensions, you can achieve similar results using:
Object.fromEntries(arr.map(...))
reduce()
Map
Choose the method that best fits your use case and environment.