I have a type MyType
type MyType = {
a?: {c: string},
b?: {e: string},
}
that contains optional nested objects. I want to create a function getDefaultValue that accepts a key K of MyType and returns a default representation of the nested object that is specified by key K.
function getDefaultValue<K extends keyof MyType>(key: K):Required<MyType>[K] {
if (key === 'a') return {c: 'hello'}
return {e: 'hello'}
}
const variable: Required<MyType>['a'] = getDefaultValue('a')
I get the following typescript errors:
TS2322: Type '{ c: string; }' is not assignable to type 'Required<MyType>[K]'.
Type '{ c: string; }' is not assignable to type '{ c: string; } & { e: string; }'.
Property 'e' is missing in type '{ c: string; }' but required in type '{ e: string; }'.
TS2322: Type '{ e: string; }' is not assignable to type 'Required<MyType>[K]'.
Type '{ e: string; }' is not assignable to type '{ c: string; } & { e: string; }'.
Property 'c' is missing in type '{ e: string; }' but required in type '{ c: string; }'.