I have the following initial object
const initialValues = { name: 'Jon', email: 'jon@me.com' }
I would like to create an identical object except where all the values are boolean
and default to false
. Like so
const expected = { name: false, email: false }
I created the following function which does what I want
const expected = cloneWithDefaults<typeof initialValues>(initialValues)
function cloneWithDefaults<T>(values: T) {
type U = { [K in keyof T]: boolean }
const keys = Object.keys(values) as Array<keyof T>
const partial: Partial<U> = keys.reduce<Partial<U>>((acc, cur) => {
acc[cur] = false
return acc
}, {})
const final = partial as U
return final
}
I also created a second version which does not use reduce
function createCloneWithDefaultsV2<T extends { [key: string]: unknown }>(values: T) {
type U = { [K in keyof T]: boolean }
const keys = Object.keys(values) as Array<keyof U>
const partial: Partial<U> = {}
for (let k in keys) {
partial[k] = false
}
const final = partial as U
return final
}
I wonder if there is a better / more succinct way of doing this. In particular I would like to get rid of the two uses of as
if possible.
In the v2 I wonder if there is any preference for unknown
as opposed to any
.