You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

15 lines
672 B

2 years ago
  1. // 第二个类型变量受第一个类型变量约束
  2. // Key 受 Type 约束(Key 要满足 Type 中的属性)
  3. function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) {
  4. return obj[key]
  5. }
  6. getProp({ name: 'jack', age: 20}, 'age') // 第二个参数要满足第一个参数的属性,可以是 age 或 name
  7. getProp({ name: 'jack', age: 20}, 'name')
  8. // 补充
  9. getProp(20, 'toFixed') // 20 是 number 类型,toFixed 是 number 类型能够访问的方法
  10. getProp('abc', 'split')
  11. getProp('abc', 1) // 1表示索引,字符串像一个数组一样,可以通过数组的索引的方式来访问
  12. getProp(['a'], length)
  13. getProp(['a'], 1000)