I have the following initial object
const initialValues = { name: 'Jon', email: '[email protected]' }
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.
unknown? You don't use the value in your function and there seems to be no requirement to limit the type of your values in any way. So if you want to accept any type an this place, any and unknown should be ok here. (afaik there's no difference here because you do not access the value)anyas opposed tounknownjust curious if there is a preference in this scenario.