Keyof 运算符
一句话解释
keyof 运算符 takes 对象类型 and 返回 union 的它的属性 names (键), 启用类型-safe 属性 access.
用大白话说
keyof 运算符 extracts 键的 对象类型 as union 的字符串 literal 类型. For type T = { a: string; b: number }, keyof T 是 "" | "b".
This is useful for creating type-safe property accessors, generic functions that work with any property, and mapped types. Combined with indexed access types (T[K]), it enables powerful type-level programming.
For example, 函数 获取<T, K extends keyof T>(obj: T, 键: K): T[K] lets you access any property of any object with full type safety — the return type matches the property's type.
示例
typescript
interface Person { name: string; age: number; }
type PersonKey = keyof Person; // "name" | "age"
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const p: Person = { name: "Alice", age: 30 };
const n = get(p, "name"); // type: stringkeyof extracts 键 as union. 获取函数 uses keyof for 类型-safe 属性 access.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。