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.
 
 
 
 
 

16 lines
672 B

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