#TS won't complain comparing a key value
1 messages · Page 1 of 1 (latest)
!:unsafe-keys
`!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>;
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
Got it. Shouldn't it be called "safeKeys" though?
Would want to avoid the slower Object.keys() path, is it a good idea to do this? (also, can I cast the key right in the for in line?)
https://www.typescriptlang.org/play?strict=false&strictPropertyInitialization=false&noImplicitThis=false&noImplicitReturns=false&ssl=1&ssc=1&pln=2&pc=1#code/MYGwhgzhAECyD2ATGBvAUASDAfgFzQBcAnAVwFNMAjPQ0igXzSYDMSA7YAgS3jemYCMACgC2A-AmQAaaCIBMEpBACU0dBmbwi0ISDIFoAa2hc+Y1eozBeEAwCtoAXh3HIRsgE94zOEujLMDC4fIQdHcOgAImsRAAdwUwgAcXgkSItAjEDGDAwAejyTEIBCIWNTWTllDNyC6Ax5AG1DAF0nWQFmlsC6nMZGNCA
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@harsh steppe Here's a shortened URL of your playground link! You can remove the full link from your message.
well no, it's explicitly unsafe
i don't mean to use that snippet, but the explanation there is relevant
if it's not thousands of properties, then speed probably shouldn't be a concern
casting is never really a good idea. with the function as it is, you can't be sure that k is actually a keyof Mods unless you're completely confident about how you call it
" unless you're completely confident about how you call it" I can
can I cast the key right in the for in line?
that it's always going to be in that shape?
no, that syntax isn't allowed
I guess so, it's an internal class
I think const j = (k as keyof typeof param1) is better