先看下这里的使用代码
const a = {
name:'000',
age:12,
sex:true
}
type A = typeof a
type keyA = keyof A
type valueA = A[keyA]
const b = {
name:'000',
age:12,
sex:true
} as const
type B = typeof b
type keyB = keyof B
type valueB = B[keyB]
1.使用后as const后变成只读了
2.使用as const后每个值的类型变成了具体的值
比如说有个函数他的入参必须是b里每项的value值,出参必须是b里每项的key值
这里可以使用valueB来指定入参类型,在后期迭代的时候不用一个一个手动添加 e:'000'|12|true|.....
const b = {
name:'000',
age:12,
sex:true
} as const
type B = typeof b
type keyB = keyof B
type valueB = B[keyB]
// 比如说有个函数他的入参必须是b里每项的value值,出参必须是b里每项的key值
const getkeyFromValue = (e:valueB):keyB => {
for (const key in b) {
if (b.hasOwnProperty(key) && b[key] === e) {
return key as keyB; // 返回找到的键
}
}
return undefined;
}
getkeyFromValue(12) // age
这里的代码还可以简化,使用一行代码代替
type B = typeof b
type keyB = keyof B
type valueB = B[keyB]
type valueB = typeof b[keyof typeof b]
再高级点封装成泛型函数,这里使用T代替了typeof b很巧妙的用法
type ValueOf<T> = T[keyof T]; // 提取对象中所有值的类型
// 泛型函数,接受任意对象和值,返回对应的键
function getKeyFromValue<T>(obj: T, value: ValueOf<T>): keyof T | undefined {
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key] === value) {
return key as keyof T; // 返回找到的键
}
}
return undefined;
}
// 示例对象
const b = {
name: '000',
age: 12,
sex: true
} as const;
// 使用泛型函数
const result = getKeyFromValue(b, '000'); // 应该返回 'name'
console.log(result); // 输出: 'name'
// 测试其他值
console.log(getKeyFromValue(b, 12)); // 输出: 'age'
console.log(getKeyFromValue(b, true)); // 输出: 'sex'
console.log(getKeyFromValue(b, 'notFound')); // 输出: undefined