tamuhey
tamuhey

Reputation: 3535

Make a part of interface not to be optional

I want to change a property x of the interface Foo not to be Optional:

// thirdparty.ts
interface Foo {
  x?: ComplexObjectType,
  y?: string,
  z?: string
}

// main.ts
import { Foo } from "thirdparty";
type Bar = // same as `Foo` except that the field `x` is public

How to do that?

Upvotes: 0

Views: 51

Answers (2)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10137

If you want to make one property required, which you know in advance, you can easily do it like this:

type Bar = Foo & { x: Foo['x'] }

const bar: Bar = {}; // Property 'x' is missing in type '{}' but required in type...

Live on the playground

Upvotes: 2

Karol Majewski
Karol Majewski

Reputation: 25790

interface Foo {
  x?: ComplexObjectType,
  y?: string,
  z?: string
}

type Require<T, K extends keyof T> = T & {
    [P in K]-?: T[P]
  };

type Bar = Require<Foo, 'x'>;

Upvotes: 1

Related Questions