【TypeScript】TypeScript进阶
在TypeScript中,进阶主要涉及更复杂的类型系统、工具和最佳实践。以下是一些进阶主题的示例代码:
- 类型保护 (Type Guards)
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
let pet = getSmallPet();
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
- 类型断言
let fishPet = <Fish>getSmallPet();
fishPet.swim();
- 泛型
function createMap<Key, Value>(initialData: Map<Key, Value>): Map<Key, Value> {
let newMap = new Map<Key, Value>();
initialData.forEach((value, key) => newMap.set(key, value));
return newMap;
}
let stringMap = createMap<string, number>([
["one", 1],
["two", 2]
]);
- 接口 vs. 类
interface Point {
x: number;
y: number;
}
class PointClass implements Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
- 混合类型
type Descriptor =
{ kind: "number", value: number } |
{ kind: "string", value: string };
let numberDescriptor: Descriptor = { kind: "number", value: 123 };
let stringDescriptor: Descriptor = { kind: "string", value: "hello" };
- 类型别名
type Point = {
x: number;
y: number;
};
let origin: Point = { x: 0, y: 0 };
这些代码示例展示了TypeScript中的一些高级特性,它们可以用来构建复杂的类型和应用程序。
评论已关闭