Typescript 从其他包扩展接口
我有一些在其他文件中定义的接口IPProduct和ICategory,我无法编辑它们Typescript 从其他包扩展接口,typescript,Typescript,我有一些在其他文件中定义的接口IPProduct和ICategory,我无法编辑它们 interface IProduct { id: number, name: string, } interface ICategory { id: number, name: string, products: IProduct[], } 我如何扩展IPProduct,使其也包含另一个属性价格?因此,个人主义应该是这样的: interface ICategory { id: numb
interface IProduct {
id: number,
name: string,
}
interface ICategory {
id: number,
name: string,
products: IProduct[],
}
我如何扩展IPProduct,使其也包含另一个属性价格?因此,个人主义应该是这样的:
interface ICategory {
id: number,
name: string,
products: {
id: number,
name: string,
price: number
}
}
您可以创建一个新的ICategoryProduct类型,如下所示:
type ICategoryProduct = {
price: number
} & IProduct
然后使用ICategory界面中的类型:
interface ICategory {
id: number,
name: string,
products: ICategoryProduct
}
或者,您可以在ICategory中定义产品类型:
但是,我认为产品需要是一个阵列,然后ICategory接口将如下所示:
interface ICategory {
id: number,
name: string,
products: Array<{
price: number
} & IProduct>
}
我想你在找更简单的。你能再做一个这样的界面吗
interface IProductWithPrice extends IProduct {
price: number;
}
您提到不能直接编辑IPProduct和ICategory。您可以简单地重复IPProduct接口并向其添加属性。向接口添加属性,它将按预期工作 文件放在您够不着的地方: 接口IPProduct{ 身份证号码:, 名称:string, } 您的文件: 从“someApi”导入{IPProduct}; 接口IPProduct{ 身份证号码:, 名称:string, 价格:编号//新物业 } 常数乘积:IPProduct={ id:'1241534', 名字:'胡萝卜', 价格:2.0 };
IPProduct和ICategory在其他文件中定义,我无法编辑。其次,ICategory包含了大量的道具,我不想再写了。只是想以category.products可能还包含price prop的方式对其进行扩展。您能展示一下IPProduct和ICategory是如何嵌入到另一个文件中的吗?该文件是一个模块,是一个声明文件.d.ts,它们是否包含在环境模块声明中,如declare module xxx{}?
interface IProductWithPrice extends IProduct {
price: number;
}