学习 Typescript 6(类型断言 | 联合类型 | 交叉类型)
// 类型断言
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
// 联合类型
let myFavoriteNumber: string | number;
myFavoriteNumber = "I don't like numbers";
myFavoriteNumber = 123;
// 交叉类型
type Desktop = {
screen: string;
keyboard: string;
};
type Laptop = {
screen: string;
keyboard: string;
trackpad: string;
};
type Combined = Desktop & Laptop;
let myCombined: Combined = {
screen: "Retina",
keyboard: "ISO",
trackpad: "Precise"
};
这个代码示例展示了如何在TypeScript中使用类型断言、联合类型和交叉类型。类型断言允许你明确地指定一个值的类型,联合类型允许一个变量同时有多种类型,而交叉类型则是将多个类型的特性组合在一起。这些概念是TypeScript中类型系统的核心部分。
评论已关闭