An object literal creates an object directly by placing property names and values inside braces. Use colons between names and values, commas between properties, and assign the result to a variable, pass it to a function, or store it in an array. section 3.5
TypeScript checks an object literal through its shape: the combination of property names and value types. A type alias can name that shape, and a method can return an object literal that matches it. section 2.2.6
Product objects
These literals create products with name and price properties: hat has a numeric price, while boots has a string price. Converting both values with Number produces a total of 200.
Shape checking exposes inconsistent collections. If an array combines objects where umbrella lacks price, accessing prod.price produces a compiler error; the safe shared shape contains only name. section 10.2
Listing 2.25 Using a shape type in the todoCollection.ts file in the src folder
import { TodoItem } from "./todoItem";
type ItemCounts = {
total: number,
incomplete: number
}
export class TodoCollection {
private nextId: number = 1;
private itemMap = new Map<number, TodoItem>();
constructor(public userName: string, todoItems: TodoItem[] = []) {
todoItems.forEach(item => this.itemMap.set(item.id, item));
}
addTodo(task: string): number {
while (this.getTodoById(this.nextId)) {
this.nextId++;
}
this.itemMap.set(this.nextId, new TodoItem(this.nextId, task));
return this.nextId;
}
getTodoById(id: number) : TodoItem {
return this.itemMap.get(id);
}
getTodoItems(includeComplete: boolean): TodoItem[] {
return [...this.itemMap.values()]
.filter(item => includeComplete || !item.complete);
}
markComplete(id: number, complete: boolean) {
const todoItem = this.getTodoById(id);
if (todoItem) {
todoItem.complete = complete;
}
}
removeComplete() {
this.itemMap.forEach(item => {
if (item.complete) {
this.itemMap.delete(item.id);
}
})
}
getItemCounts(): ItemCounts {
return {
total: this.itemMap.size,
incomplete: this.getTodoItems(false).length
};
}
}
Inspect a complete TypeScript example that names an object shape with an ItemCounts type alias and returns a matching object literal from a collection method. section 2.2.6

