首页 > 解决方案 > 扩展嵌套 typescript 接口

问题描述

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

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

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

现在假设我正在编写一个函数,它需要一辆汽车并用它做一些事情

/* 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 代码生成器。可以对其进行一些自定义,但不幸的是,我不知道如何让它在漂亮的分隔界面中生成所有内容。

标签: javascripttypescriptgraphqlcode-generation

解决方案


使用 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;

推荐阅读