7. keyof 和 typeof 关键字有何用途?
约 175 字小于 1 分钟
2025-06-09
1、keyof
操作符
keyof 操作符用于获取对象类型的所有键的联合类型。它的语法如下:
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
2、typeof
操作符
typeof 操作符用于获取一个变量或表达式的类型。它的语法如下:
typeof x;
其中,x
是一个变量或表达式。 例如:
const str = "hello";
type StrType = typeof str; // string
3、区别
特性 | typeof | keyof |
---|---|---|
操作对象 | 变量 | 类型 (对象结构) |
返回结果 | 该变量的类型 | 键名的集合 |
典型用途 | 获取变量的类型 | 获取对象键名集合 |
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于