javascript - 扩展嵌套 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 代码生成器。可以对其进行一些自定义,但不幸的是,我不知道如何让它在漂亮的分隔界面中生成所有内容。
解决方案
使用 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;
推荐阅读
- java - RestController GetMapping,RequestMapping 不工作,
- node.js - 使用 nodejs 和 fetch 跨域 httponly cookie
- javascript - Javascrypt复制到剪贴板功能仅复制第一行
- python - 如何访问该表中的所有文本元素(scrapy)?
- node.js - Express,React TypeError:无法读取未定义cookie的属性“令牌”
- c# - ASP.NET Core 6 - 带有附加元数据的异步流
- typescript - TypeScript+NextJS 解构
- google-sheets - 公式结果为范围输出错误的数字
- ruby - 在最新的 alpine linux 映像上安装 Ruby 时未初始化的常量 Psych (NameError)
- python - 更改工作表中的现有图像大小