1. Welcome and Icebreaker:
- If you could create a dictionary for any topic, what would it be about?
2. Outline the Session:
- We’ll learn about index signatures in TypeScript: how to define objects with dynamic keys.
- Learning Outcomes: Understand how to type objects with unknown or variable property names.
- Let’s get started!
3. Concept Explanation:
- Index Signatures allow you to type objects with keys that are not known ahead of time.
- Syntax:
interface StringMap {
[key: string]: string;
}
- You can use index signatures for objects like dictionaries, maps, or caches.
- The key type is usually
string or number (but not both in the same signature).
- You can combine index signatures with other properties.
4. Live Coding Demonstration:
// String index signature
interface PhoneBook {
[name: string]: string;
}
const contacts: PhoneBook = {
Alice: "123-4567",
Bob: "987-6543"
};
console.log(contacts["Alice"]);
// Number index signature
interface ScoreMap {
[id: number]: number;
}
const scores: ScoreMap = {
1: 100,
2: 95
};
console.log(scores[1]);
// Index signature with other properties
interface Settings {
theme: string;
[key: string]: string;
}
const userSettings: Settings = {
theme: "dark",
fontSize: "16px",
language: "en"
};
console.log(userSettings);
5. Tasks:
- Short Exercise:
- Define an interface
ErrorMessages with string keys and string values.
- Create an
ErrorMessages object with at least three error codes and their messages.
- Define an interface
ProductStock with number keys and number values.
- Create a
ProductStock object and add stock counts for three products.