打字稿中的“复合类型”

时间:2018-06-06 19:51:28

标签: typescript

我记得在Typescript中看到一个功能,其中一个类型可以由另一个类型的属性组成,也可以由它自己组成。但我不确定我是否正确记得它。请考虑以下事项:

// 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
};

这似乎有效,但我不确定它是否按照我的想法行事。这样的功能是否存在,如果存在,它的名称是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用交叉点类型

// 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
};
相关问题