benhowdle89
benhowdle89

Reputation: 37464

TypeScript provide default values for missing keys of a Type

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?

Upvotes: 2

Views: 840

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 37918

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
}

Playground

Upvotes: 1

bugs
bugs

Reputation: 15313

Types only exist at compile time, so the exact thing you're trying to do is not possible.

A simpler alternative would be something like

type TestStatus = {
    foo: boolean;
    bar: boolean;
    baz: boolean;
}

const defaultTestStatus: TestStatus = {
    foo: false,
    bar: false,
    baz: false
}


const merge = (partialStatus: Partial<TestStatus>): TestStatus => ({
    ...defaultTestStatus,
    ...partialStatus
})

Upvotes: 2

Related Questions