How do i make Intersection type optional in typescript

Viewed 1518
interface TypeA {
  a: string
  b: string
}

interface TypeB {
  c: string
}

now i want to make a TypeC, a and b is optional, c is required.

interface TypeC {
  a?: string
  b?: string
  c: string
}

are there any shortcut to make this? for example:

// type TypeC = TypeA? & TypeB

I think it's useful when TypeA is huge

2 Answers

playground

interface TypeA {
  a: string
  b: string
}

interface TypeB {
  c: string
}

// First way using extends and Partial
interface TypeC extends Partial<TypeA>, TypeB {
  // ...
}

// Second way using & and Partial
type TypeD = Partial<TypeA> & TypeB;

const variableC: TypeC = {
  c: '',
};

const variableD: TypeD = {
  c: '',
};

If you want to disallow excess properties, that is to get a TS error in this case:

const variableC: TypeC = {
  a: '',
  c: '',
};

The solution I've found is to use ts-toolbelt and it's Union.Strict type:

type TypeD = Union.Strict<(TypeA & TypeB) | TypeB>;
Related