Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Composite type" in TypeScript

Tags:

typescript

I recall seeing a feature in TypeScript where a type could be composed of another type's properties as well as it's own. But I'm not sure if I'm remembering it correctly. Consider the following:

// type or interface
type X = {
  a: number
};

// type or interface
// composes properties from X ???
type XPlus = {
  [P: keyof X], // include properties from X
  b: boolean    // add a new property
};

// instance includes properties from both X and XPlus
const instance: XPlus = {
  a: 100,
  b: false
};

This seems to work, but I'm not sure it's doing what I think it is. Does such a feature exist, and if so, what's it called?

like image 268
Josh M. Avatar asked Jan 27 '23 23:01

Josh M.


1 Answers

You can just use an intersection type

// type or interface
type X = {
    a: number
};


type XPlus = X & {
    b: boolean    // add a new property
};

// instance includes properties from both X and XPlus
const instance: XPlus = {
    a: 100,
    b: false
};
like image 195
Titian Cernicova-Dragomir Avatar answered Jan 31 '23 21:01

Titian Cernicova-Dragomir