数组的打字稿泛型

时间:2020-04-14 05:03:54

标签: javascript typescript

我需要从我的课堂扩展Array的泛型。 如何正确做?

export interface DeliveryMethod {
  readonly id: string;
  readonly company: string;
  readonly cost: number;
  readonly threshold: number;
  readonly intervals: Array<Interval>;
  readonly paymentMethods: Array<PaymentMethod>;
}

export interface Delivery {
  selected: SelectedDelivery;
  available: { [key : string] : Array<T extends DeliveryMethod>};
}

找不到名称'T'.ts(2304)

available: { [key : string] : Array<T extends DeliveryMethod>};

例如,我需要类似的东西:

const Delivery = {
   selected :{/*data inside*/},
   available:{
      pickup: [<Pickup>{},<Pickup>{}],
      courier: [<Courier>{},<Courier>{}]  
   }
}

2 个答案:

答案 0 :(得分:2)

@aopanasenko的答案很好。我想完成它,添加解决多种规格问题的方法。

如果available的属性不是很多,并且它们是固定且稳定的,那么您可以考虑在Delivery界面中将它们全部列出:

interface Delivery<T extends DeliveryMethod, U extends DeliveryMethod> {
  available: { [key : string] : Array<T | U>};
};

然后,您可以像这样定义delivery对象:

const delivery: Delivery<Pickup, Courier>

如果您不了解属性的先验知识,那么您需要一种将属性名称链接到TypeScript类型的方法,例如,我为映射添加了一个available对象:

interface Delivery {
  available: { [key: string]: Array<DeliveryMethod> | null };
};

const delivery: Delivery = {
  available: {}
}

const available: {
  pickup: Pickup[] | null,
  courier: Courier[] | null
} = {
  pickup: null,
  courier: null
};

delivery.available = { ...delivery.available, ...available };

通过这种方式,可以正确进行类型检查。我还添加了| null以提供示例,您可以将其删除。

答案 1 :(得分:0)

更新

如@AndreaSimoneCosta在评论中所述,以下代码应该可以工作:

export interface DeliveryMethod {
  readonly id: string;
  readonly company: string;
  readonly cost: number;
  readonly threshold: number;
  readonly intervals: Array<Interval>;
  readonly paymentMethods: Array<PaymentMethod>;
};

export interface Delivery<T extends DeliveryMethod = DeliveryMethod> {
  selected: SelectedDelivery;
  available: { 
    [key : string] : Array<T>
  };
};

您应该在Delivery接口名称之后的尖括号中定义通用类型参数列表:

export interface DeliveryMethod {
  readonly id: string;
  readonly company: string;
  readonly cost: number;
  readonly threshold: number;
  readonly intervals: Array<Interval>;
  readonly paymentMethods: Array<PaymentMethod>;
};

export interface Delivery<T extends DeliveryMethod> {
  selected: SelectedDelivery;
  available: { 
    [key : string] : Array<T>
  };
};