泛型 groupBy 函数 在编辑器中打开 function groupBy<T, K extends string>(items: T[], key: (item: T) => K): Record<K, T[]> {
const groups = {} as Record<K, T[]>;
for (const item of items) {
(groups[key(item)] ??= []).push(item);
}
return groups;
}
const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
console.log(groupBy(words, (w) => w[0]));
用 switch 处理可辨识联合类型 在编辑器中打开 type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rect":
return shape.width * shape.height;
}
}
const shapes: Shape[] = [{ kind: "circle", radius: 1 }, { kind: "rect", width: 2, height: 3 }];
for (const s of shapes) console.log(s.kind, area(s).toFixed(2));
抽象类与继承 在编辑器中打开 abstract class Animal {
constructor(protected readonly name: string) {}
abstract sound(): string;
speak(): string {
return `${this.name} says ${this.sound()}`;
}
}
class Dog extends Animal {
sound() {
return "woof";
}
}
class Cat extends Animal {
sound() {
return "meow";
}
}
const pets: Animal[] = [new Dog("Rex"), new Cat("Tom")];
pets.forEach((pet) => console.log(pet.speak()));
数字枚举与反向映射 在编辑器中打开 enum Status {
Todo,
Doing,
Done,
}
const tasks: { title: string; status: Status }[] = [
{ title: "write", status: Status.Done },
{ title: "test", status: Status.Doing },
{ title: "ship", status: Status.Todo },
];
for (const task of tasks) {
console.log(task.title.padEnd(6), Status[task.status]);
}
异步重试辅助函数 在编辑器中打开 async function retry<T>(task: () => Promise<T>, times: number): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await task();
} catch (error) {
console.log(`attempt ${attempt} failed: ${(error as Error).message}`);
if (attempt === times) throw error;
}
}
}
let calls = 0;
const flaky = async () => {
calls++;
if (calls < 3) throw new Error("not yet");
return "ok";
};
console.log(await retry(flaky, 5));