A common pain point when using TypeScript is when you have this Object.keys function here. My object here has keys a b and c but when I try to iterate over its keys when I've extracted them from Object.keys, the key is typed as a string.
That means that when I try to access it I get this horrible long type error. No index signature with parameter of type string was found in type a b c.
export const myObject = {
a: 1,
b: 2,
c: 3,
}
Object.keys(myObject).forEach((key) => {
console.log(myObject[key])
})
So this really should be typed as keyof myObject and the way to get around this is to create your own Object.keys function.
So we'll create our function objectKeys which has a generic Obj. We'll set that as the type for our argument obj and then set the return type to be an array of keyof Obj.
const objectKeys = <Obj>(obj: Obj): (keyof Obj)[] => {}
Then we'll return Object.keys(obj) as (keyof Obj)[]. We are using the as to make a type assertion. This tells the compiler to infer the result of Object.keys(obj) to be an array of the objects keys as strings.
const objectKeys = <Obj>(obj: Obj): (keyof Obj)[] => {
return Object.keys(obj) as (keyof Obj)[]
}
So now if we go objectKeys(myObject) then key is typed as a b or c.
objectKeys(myObject).forEach((key) => {
console.log(myObject[key])
})
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.