#how can I do Object.keys as const

1 messages · Page 1 of 1 (latest)

sinful thunder
#

Hi, I have a function that I usually pass
const input = ["a", "b", "c"] as const
myFunc({input});

But now I have an object
const myObject = {a:"a", b:"b",c:"c"}
when I do this ts does not like it
Object.keys(myObject) as const

Is there a way I can do this?

marsh ledge
#

no, as const is for literals

#

separately, Object.keys can't be specific because:

#

!:unsafe-keys

copper starBOT
#
retsam19#0
`!retsam19:unsafe-keys`:

Since TS allows objects to have extra properties not specified in the type, it doesn't assume that all the keys on the type are the only keys on the object. This means that Object.keys returns string[] not a specific type, and for(const key in obj), key is string, (not keyof typeof obj).

If you wish to assume otherwise, this utility is often helpful:

// A signature for `Object.keys` that assumes the only keys are the ones indicated by the type
const unsafeKeys = Object.keys as <T>(obj: T) => Array<keyof T>;