1

How can I create a new interface based on optionals from another interface and make them required?

Say I have an interface like this:

interface Foo {
  test1: string;
  test2?: string;
}

from this I'm looking to create a new interface that looks like this:

interface FooDefaults {
  test2: string;
}

Then I can use that for my default values like this:

const defaults: FooDefaults = {
  test2: 'bar'
}
benjick
  • 45
  • 1
  • 5

1 Answers1

0

This is tricky one, there is open discussion about syntax around that, take a look here. Below solution based on @jcalz answer

interface Foo {
  test1: string;
  test2?: string;
}

type Defaults<T, OptionalKeys extends keyof T = { [K in keyof T]:
  ({} extends { [P in K]: T[K] } ? K : never)
}[keyof T]> = {
  [K in OptionalKeys]-?: T[K]
}

type FooDefaults = Defaults<Foo>

I would say solution is more a hack than a solution and it based in the behavior where {} extends {a?: string} but {} doesn't extend {a: string}.

Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50