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])
})
标签:function,myObject,keyof,own,key,objectKeys,operator,using From: https://www.cnblogs.com/Answer1215/p/16753705.html