keyof(K extends keyof T )
2.1版本以上 获取对象属性值转为联合类型,可用于接口,多用于函数,更语义化、更安全 www.typescriptlang.org/docs/handbo… 官方文档中写道:
The `keyof` operator takes an object type and produces a string or numeric
literal union of its keys
//keyof获取一个对象的属性名,产生一个字符串或者他的值联合类型
1.接口或者别名中 将对象的key值转为联合类型
interface Person {
name: string;
age: number
}
type Keys = keyof Person
interface Student {
key: Keys
}
const xiao: Student = {
key: "age"
}
// 获取name | age
2.函数泛型约束中keyof, 能正确地推导出指定键对应的类型,捕获语义
//静态类型系统中捕获某些操作的语义比较困难,ts的keyof来指定类型
const getList= <T extends object, K extends keyof T> (obj: T, key:K):T[K] => {
return obj[key]
}
//返回对应的属性的值
3.函数泛型约束中keyof,避免数字作为键值的不安全性
enum Ages{
A = 6,
B = 8
}
const ListName = {
[Ages.A]: "小",
[Ages.B]: "大"
}
console.log(`ListName[Ages.A]=${ListName[Ages.A]}`)
console.log(`ListName[6] = ${ListName[6]}`)
//都可以返回 小
与泛型和泛型约束结合
enum Ages{
A = 6,
B = 8
}
const ListName = {
[Ages.A]: "小",
[Ages.B]: "大"
}
function getNames<T, K extends keyof T>(key: K, Values: T): T[K]{
return Values[key]
}
console.log(`${getNames(Ages.A,ListName[Ages.A])}`)
//使用了泛型和泛型约束,从而来保证属性的安全访问