繁体   English   中英

多个类型变量的通用约束

[英]Generic constraint on multiple type variables

我为现有的库编写类型。 我遇到了为类型定义约束的问题,其中两个变量类型应该满足某些限制(T1 [T2]应该是某种类型的数组)。

我有第一个界面

interface GenericInterfaceWithArray<ElementType> {
  arrayOfElements: ElementType[];
  push: (value: ElementType) => void;
}

第二个使用前一个并且还有两个类型变量:

interface OuterInterface<
  ObjectContainingArray,
  KeyOfPropertyWithArray extends keyof ObjectContainingArray
> {
  nestedProperty: GenericInterfaceWithArray<ObjectContainingArray[KeyOfPropertyWithArray]>;
  // line above has incorrect definition because
  // ObjectContainingArray[KeyOfPropertyWithArray] is an array
  // - can I take type from 'first array element' here?
  // smth like this line below

  // GenericInterfaceWithArray<ObjectContainingArray[KeyOfPropertyWithArray][0]>;
  // this does not work:
  // `Type '0' cannot be used to index type 'ObjectContainingArray[KeyOfPropertyWithArray]'.`
}

用法:

interface InterfaceWithArrayProp {
  arrayProp: number[];
}

const myType: OuterInterface<InterfaceWithArrayProp, 'arrayProp'>;
myType.nestedProperty.push(25); // here should be validation for `number`.
// Currently I have type: `number[]`

我尝试用另一种方式定义内部接口:作为数组的通用(不太令人满意,但如果第一版没有办法则可以接受):

interface GenericInterfaceWithArray<ArrayOfElements extends Array<any>> {
  arrayOfElements: ArrayOfElements;
  push: (value: ArrayOfElements[0]) => void;
}

但是现在我有来自OuterInterface的错误: OuterInterface Type 'ObjectContainingArray[KeyOfPropertyWithArray]' does not satisfy the constraint 'any[]'.

是否可以定义T1[T2]是一个数组并将第一个元素的类型作为另一个通用接口的参数?

好的,我发现我可以使用条件类型。

type FirstArrayElement<ElementsArrayType> = ElementsArrayType extends any[] ? ElementsArrayType[0] : never;

interface OuterInterface<
  ObjectContainingArray,
  KeyOfPropertyWithArray extends keyof ObjectContainingArray
> {
  nestedProperty: GenericInterfaceWithArray<FirstArrayElement<ObjectContainingArray[KeyOfPropertyWithArray]>>;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM