#mapped types: how can I get conditionally optional keys?

6 messages · Page 1 of 1 (latest)

storm vault
#

if I'm starting with a type like...

type A = {
  b: B;
  c: C | undefined;
};

and I want to turn that into...

type AdjustedA = {
  b: B;
  c?: C | undefined;
};

basically, detecting which keys represent types that would allow undefined, and then making those keys optional,

how could I do that?

it seems like you can only make all properties optional ? or make none of them optional -? by using a single mapped type. I've been trying to compose multiple mapped types and join them together, but it really feels like the wrong approach and I'm having a hard time getting it working. would be super great if there was some mystic bit of knowledge I'm missing that would make this super easy. :p

chrome remnant
stark monolithBOT
#
mishall8399#0

Preview:```ts
type A = {
b: string
c: number | undefined
}

type UndefinableKeys<T> = {
[K in keyof T]: undefined extends T[K] ? K : never
}[keyof T]

type UnwrapIntersection<T> = {
[K in keyof T]: T[K]
}

type Adjust<T> = UnwrapIntersection<
Partial<Pick<T, UndefinableKeys<T>>> &
Omit<T, UndefinableKeys<T>
...```

twilit meteor
#

Partial is a mapped type here so yeah

#

you don't really need to Pick into the partial, technically

stark monolithBOT
#
that_guy977#0

Preview:```ts
type A = {
b: string
c: number | undefined
}

type UndefinableKeys<T> = {
[K in keyof T]: undefined extends T[K] ? K : never
}[keyof T]

type Adjust<T> = Partial<T> &
Omit<T, UndefinableKeys<T>>

type AdjustedA = Adjust<A>

type Expand<T> = {
...```