#TS won't complain comparing a key value

1 messages · Page 1 of 1 (latest)

sinful gardenBOT
golden gate
#

!:unsafe-keys

sinful gardenBOT
#
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>;
golden gate
#

besides that, you've explicitly said that you allow excess keys by saying M extends Mods

#

Extract<keyof M, string> is not "a" | "b", that's Extract<keyof Mods, string>
M might have more keys

harsh steppe
#

Got it. Shouldn't it be called "safeKeys" though?

#
sinful gardenBOT
#

@harsh steppe Here's a shortened URL of your playground link! You can remove the full link from your message.

ricmed#0

Preview:ts class Mods { a?: true ...

golden gate
golden gate
golden gate
harsh steppe
#

" unless you're completely confident about how you call it" I can

#

can I cast the key right in the for in line?

golden gate
#

that it's always going to be in that shape?

golden gate
harsh steppe
#

I think const j = (k as keyof typeof param1) is better

golden gate
#

that doesn't change anything

#

why do you need to iterate over the keys of an internal class anyways?

#

key iteration would generally be used for records or unknown structures

#

since it's basically reflection

harsh steppe
#

you're right

#

thanks!