2

I have an interface containing some optional fields

interface Config {
  name: string,
  context?: string,
  value?: number,
  type: string
}

I would like to extract all optional fields and their values

The result should look like this:

type OptionalConfig = ExtractOptionalProperties<Config>

// {
//   context?: string,
//   value?: number,
// }

I found a way to extract all optional keys but have no idea how to extract also the values. Is it possible with Typescript?

Joozty
  • 460
  • 2
  • 12
  • 40

1 Answers1

2

You can use a mapped type for that:

type ExtractOptionalProperties<T extends object> = {
    [key in OptionalPropertyOf<T>]: T[key];
}

T[key] is what gives you the property type.

Playground Link

It's also possible to modify the modifiers, although with the OptionalPropertyOf from the answer you linked, the optionality has been converted to a union with undefined.

You haven't said you do, but if you wanted to remove the optionality, you could use Exclude<T[key], undefined>:

type ExtractOptionalProperties<T extends object> = {
    [key in OptionalPropertyOf<T>]: Exclude<T[key], undefined>;
}

In the result, context would be string instead of string | undefined, and value would be number instead of number | undefined. (Playground link) But again, you didn't say you wanted to do that, just wanted to show that there's more you can do if you like.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875