代码之家  ›  专栏  ›  技术社区  ›  Josh M.

typescript中的“复合类型”

  •  2
  • Josh M.  · 技术社区  · 8 年前

    我记得在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 回复  |  直到 8 年前
        1
  •  4
  •   Titian Cernicova-Dragomir    8 年前

    您可以使用交叉点类型

    // 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
    };
    
    推荐文章