【问题标题】:Extend nested typescript interface扩展嵌套 typescript 接口
【发布时间】:2020-10-30 10:37:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript typescript graphql code-generation


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但问题是我无法控制原始类型定义,它们是生成的代码。我想知道是否有一种简单的方法可以访问生成类型的“子类型”。
    • 也许尝试一下 Transportation['Vehicle ']['Car'] 会有所帮助。但也许把你得到的回应放进去更容易:link我认为从长远来看这会更适合
    • 我原本打算做这样的事情(虽然我使用VS Code Extension)但我们必须不时更改类型,最好不要有一堆多余的要更新的接口。
    • 实际上Transportation['Vehicle']['Car'] 完美运行,谢谢!想要将其添加为答案以便我接受?
    猜你喜欢
    • 2020-06-09
    • 2016-07-06
    • 2017-10-21
    • 2020-04-09
    • 2018-06-20
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多