[Typescript] Tips: Create your own 'objectKeys' function using generics and the 'keyof' operator

The looseness of Object.keys can be a real pain point when using TypeScript. Luckily, it's pretty simple to create a tighter version using generics and the keyof operator.

export const myObject = {
  a: 1,
  b: 2,
  c: "3"
}

Object.keys(myObject).forEach((key) => {
  console.log(myObject[key])
})

This is because keyis type of string, instead of 'a' | 'b' | 'c'

export const myObject = {
  a: 1,
  b: 2,
  c: "3"
}

const objectKeys = <T>(obj: T): (keyof T)[] => {
  return Object.keys(obj) as (keyof T)[]
}

objectKeys(myObject).forEach((key) => {
  console.log(myObject[key])
})

 

posted @ 2022-10-04 14:16  Zhentiw  阅读(17)  评论(0编辑  收藏  举报