TypeScript 的类型操作符 typeof
文章类型:TypeScript
发布者:hp
发布时间:2025-03-18
1:定义:typeof是TypeScript中的一个关键字,用来获取变量或者表达式的类型
2:用途:
在运行时=>用来获取一个值的类型。返回类型
let num = 42;
console.log(typeof num); // 输出 "number"
在静态类型检查时=>用来获取一个已有变量的类型,主要用于类型推断,在编译时检查类型
let num = 42;
type NumType = typeof num; // NumType 被推断为 number
let anotherNum: NumType; // 这里 anotherNum 的类型就是 number
anotherNum = 24; // 这是合法的赋值
// anotherNum = "24" // 这会报错,因为字符串不是 number 类型
1:类型推断
const person = {
name: "John",
age: 30
};
type PersonKeys = keyof typeof person; // PersonKeys被推断为 "name" | "age"
const key: PersonKeys = "age"; // 合法
2:与keyof联合使用
const colors = {
red: "red",
blue: "blue"
};
type ColorKeys = keyof typeof colors; // ColorKeys 被推断为 "red" | "blue"
let myColor: ColorKeys = "red"; // 合法赋值
// myColor = "green"; // 非法赋值,因为"green"不是ColorKeys之一
3:类型别名与复用:快速创建类型别名,避免重复定义相同类型
const colors = ["red", "green", "blue"] as const;
type Color = typeof colors[number]; // "red" | "green" | "blue"
4:类型保护与分支处理:运行时检查类型,减少潜在的类型错误
function logValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
5:枚举类型信息提取:可获取其类型定义而非具体值
enum Status { Active, Inactive }
type StatusType = typeof Status; // 获取枚举类型,而非具体值
6:类型映射与泛型约束:可实现动态类型映射或约束泛型参数的范围
function clone<T>(obj: T): typeof obj {
return { ...obj };
}
1:静态类型推导:动态获取变量或值的类型信息,支持编译时检查
2:类型别名复用:减少冗余类型定义,提升代码可维护性
3:运行时类型保护:结合条件语句实现类型分支处理
4:枚举类型处理:提取枚举类型定义,增强类型安全性
5:泛型与类型映射:动态约束泛型参数或映射复杂类型结构