There might be an incredibly obvious answer, but how does one do the following:
type testStatus = {
foo: boolean;
bar: boolean;
baz: boolean;
}
const makeDefaults = (o: Partial<testStatus>) => {
const keys = // array of `testStatus` keys?
keys.forEach(k => !(k in o) && (o[k] = false)) // provide a default value for missing keys
return o
}
const obj: Partial<testStatus> = { foo: true, bar: false }
const defaultedObj = makeDefaults(obj) // { foo: true, bar: false, baz: false }
Basically retrieve all the keys from a Type, to loop through?
You can't get keys as value from type because type doesn't exist at runtime. If type is simple and has same value type for all its keys as in example - you can create an array of keys first, then create the type from it:
const KEYS = ['foo', 'bar', 'baz'] as const;
type testStatus = { [K in typeof KEYS[number]]: boolean };
const makeDefaults = (o: Partial<testStatus>) => {
KEYS.forEach(k => !(k in o) && (o[k] = false))
return o
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments