从其他包扩展接口

时间:2019-10-07 04:12:18

标签: typescript

我有IProductICategory接口,它们在其他文件中定义,我无法编辑。

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
  }
}

3 个答案:

答案 0 :(得分:1)

您提到不能直接编辑IProductICategory。您只需重复 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;
}