繁体   English   中英

扩展嵌套typescript接口

[英]Extend nested typescript interface

我有一些使用代码生成器创建的复杂 typescript 类型,我希望能够使用这些类型的一部分而不必再次定义整个事物。

例如,我生成的界面可能看起来像这样(大大简化)

type Transportation = {
  vehicle: { 
    truck: {...}
    car: {
      make: string
      model: string
      weight: string
      ...
    }
  }
  boat: {...}
  ...
}

现在说我正在写一个 function,它可以带一辆车并用它做一些事情

/* This type won't work, I'm asking if there is a proper way to do this*/
processCar(car: Transportation.vehicle.car) {
  //TODO: process the car
}

const transport: Transportation = {...}
processCar(transport.vehicle.car)

有没有一种方法可以根据现有类型的一部分创建类型,而不必将整个汽车项目定义为其自己的类型或接口? 它可以用接口或其他东西扩展吗? 谢谢!

对于上下文,我的复杂生成类型来自graphql 代码生成器 可以对其进行一些自定义,但不幸的是,我不知道如何让它在漂亮的分隔界面中生成所有内容。

使用 Transportation['Vehicle']['Car'] 就可以了。

如果类型可以访问,那么输入它的更好方法是,然后您可以按如下方式使用它们。

你可以使用这样的命名空间

namespace Transportation {
    export namespace Vehicle {
        export interface Car {
            make: string;
            model: string;
            weight: string;
            ...
        };
        export interface Truck {
            make: string;
            model: string;
            weight: string;
            ...
        }
    }

    export interface Boat {
        ...
    }
}

let car: Transportation.Vehicle.Car;

但老实说,这种方法似乎并不是最好的情况。

通常,您只需使用一个命名空间并导出您在外部需要的每个接口。

namespace Transportation {
    //note, that the Vehicle isn't exported
    interface Vehicle {
        make: string;
        model: string;
        weight: string;
        ...
    }
    export interface Car extends Vehicle {
        doors: number;
    }
    export interface Truck extends Vehicle {
        transportmass: number;
    }

    export interface Boat {
        ...
    }
}

//let car: Transportation.Vehicle.Car; this won't work anymore
//let vehicle: Transportaion.Vehicle; won't work either
let car: Transportation.Car;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM