[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 key
is 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])
})