我有IProduct
和ICategory
接口,它们在其他文件中定义,我无法编辑。
interface IProduct {
id: number,
name: string,
}
interface ICategory {
id: number,
name: string,
products: IProduct[],
}
我如何扩展IProduct,使其也包含另一个物业价格?这样ICategory应该像这样:
interface ICategory {
id: number,
name: string,
products: {
id: number,
name: string,
price: number
}
}
答案 0 :(得分:1)
您提到不能直接编辑IProduct
和ICategory
。您只需重复 IProduct
界面并为其添加属性。向接口添加属性,它将按预期工作
file out of your reach
:
interface IProduct {
id: number,
name: string,
}
your file
:
import { IProduct } from 'someApi';
interface IProduct {
id: number,
name: string,
price: number // new property
}
const product: IProduct = {
id: '1241534',
name: 'Carrot',
price: 2.0
};
答案 1 :(得分:0)
您可以创建一个新的ICategoryProduct
类型,如下所示:
type ICategoryProduct = {
price: number
} & IProduct
然后在ICategory
界面中使用类型:
interface ICategory {
id: number,
name: string,
products: ICategoryProduct
}
或者您可以在products
中定义您的ICategory
类型:
interface ICategory {
id: number,
name: string,
products: {
price: number
} & IProduct
}
但是,我认为products
必须是一个数组,然后ICategory
接口将像这样:
interface ICategory {
id: number,
name: string,
products: Array<{
price: number
} & IProduct>
}
答案 2 :(得分:0)
我认为您正在寻找更简单的方法。你能再做一个这样的界面
interface IProductWithPrice extends IProduct {
price: number;
}