as const 已知value获取key值

先看下这里的使用代码

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值