[英]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.