Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i make Intersection type optional in typescript

Tags:

typescript

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

like image 234
Matt Avatar asked Jul 23 '26 02:07

Matt


1 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: '',
};
like image 95
Orelsanpls Avatar answered Jul 24 '26 16:07

Orelsanpls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!