是什么

可遍历类型的所有属性,keyof 将提取属性的的字面量类型,然后构成一个联合类型。 keyof 是引索类型查询操作符。keyof T;

keyoof 返回联合类型

  1. interface Person {
  2. name: string;
  3. age: number;
  4. isChina: boolean;
  5. }
  6. interface Map<T> {
  7. [K: string]: T;
  8. }
  9. class PersonClass {
  10. name = 'stone';
  11. getName(){
  12. return this.name;
  13. }
  14. }
  15. let person: keyof Person;
  16. // let person: "name" | "age" | "isChina"
  17. let person1: keyof Person[];
  18. // let person1: number | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | ... 6 more ... | "reduceRight"
  19. let person2: keyof Map<string>;
  20. // let person2: string | number
  21. let person3: keyof PersonClass;
  22. // let person3: "name" | "getName"
  23. person3 = 'name';
  24. person3 = 'getName';
  25. // person3 = 'age'; // 不能将类型“"age"”分配给类型“"name" | "getName"”。ts(2322)
  26. let k1: keyof string;
  27. // let k1: number | "length" | "toString" | "concat" | "slice" | "indexOf" | "lastIndexOf" | "charAt" | "charCodeAt" | "localeCompare" | "match" | "replace" | "search" | "split" | "substring" | ... 6 more ... | "valueOf"
  28. let k2: keyof number;
  29. // let k2: "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision"
  30. let k3: keyof boolean;
  31. // let k3: "valueOf"
  32. let k4: keyof null;
  33. // let k4: never
  34. let k5: keyof undefined;
  35. // let k5: never

keyof 保证属性的安全访问

  1. type Todo = {
  2. name: string;
  3. age: number;
  4. isChina: boolean;
  5. };
  6. let todo: Todo = {
  7. name: 'stone',
  8. age: 18,
  9. isChina: true
  10. };
  11. function prop<T extends object, K extends keyof T>(obj: T, key: K) {
  12. return obj[key];
  13. }
  14. let l_name = prop(todo, 'name');
  15. // let l_name: string
  16. let l_age = prop(todo, 'age');
  17. // let l_age: number
  18. let l_ischina = prop(todo, 'isChina');
  19. // let l_ischina: boolean
  20. // let l_address = prop(todo, 'address');
  21. // 类型“"address"”的参数不能赋给类型“"name" | "age" | "isChina"”的参数。ts(2345)
  1. enum Currency {
  2. CNY = 6,
  3. EUR = 8,
  4. USD = 10,
  5. };
  6. const CurrencyName = {
  7. [Currency.CNY]: '人民币',
  8. [Currency.EUR]: '英镑',
  9. [Currency.USD]: '美元',
  10. };
  11. function getCurrencyName<T, K extends keyof T>(map: T, key: K): T[K] {
  12. return map[key];
  13. }
  14. let name_1 = getCurrencyName(CurrencyName, Currency.CNY);
  15. let name_2 = getCurrencyName(CurrencyName, Currency.EUR);
  16. let name_3 = getCurrencyName(CurrencyName, Currency.USD);