#migrating to ts: Object.entries for filter etc.

17 messages · Page 1 of 1 (latest)

woven hound
#

Migrating js code I wrote containing code using Object.entries to give me an array which allows me to do fp style filter() etc. The object was in the role of a map. What's the best typesafe ts form for these map objects to take so I get this fp api?

#

Is it Record<K, V> ?

woven hound
#

OK seems like it's Map<K, V>

#

not sure which ts reference doc I should have looked that up in - found it on stackoverflow

sinful plinth
woven hound
#

sure

sinful plinth
#

using Record just might let extra properties exist so Object.entries itself becomes unsafe.

#

Map is a different js structure that behaves differently

#

so it's not really about ts here, just as an fyi

#

Record<string, ...> is perfectly safe as Object.entries gives out a [string, ...] anyways, with that it's equivalent to an index signature.

sinful plinth
woven hound
#

I guess the trouble was that if x is an object type with enum key, Object.entries(x).filter() was expecting a function that takes a key value tuple and the key was incorrectly typed. Array.from() didn't have the same problem when I x was defined as Map<Enumtype, T>

sinful plinth
#

right, that's because of ts allowing extra properties. Maps (and by extension, Sets) sidestep the issue by not using properties

#

!:unsafe-keys

simple cryptBOT
#
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>;
woven hound
#

hmmm ok