简体   繁体   English

多个类型变量的通用约束

[英]Generic constraint on multiple type variables

I write types for existing library. 我为现有的库编写类型。 I've faced with problem of defining constraint for type where two variable types should satisfy some limitation (T1[T2] should be an array of some type). 我遇到了为类型定义约束的问题,其中两个变量类型应该满足某些限制(T1 [T2]应该是某种类型的数组)。

I have 1st interface 我有第一个界面

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

and second one which uses previous one and also has 2 type variables: 第二个使用前一个并且还有两个类型变量:

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]'.`
}

Usage: 用法:

interface InterfaceWithArrayProp {
  arrayProp: number[];
}

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

I've tried defining inner interface in alternative way: as generic of array (less satisfying but acceptable if there is no way for first version): 我尝试用另一种方式定义内部接口:作为数组的通用(不太令人满意,但如果第一版没有办法则可以接受):

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

But now I have an error from OuterInterface : Type 'ObjectContainingArray[KeyOfPropertyWithArray]' does not satisfy the constraint 'any[]'. 但是现在我有来自OuterInterface的错误: OuterInterface Type 'ObjectContainingArray[KeyOfPropertyWithArray]' does not satisfy the constraint 'any[]'.

Is it possible to define that T1[T2] is an array and pass type of this first element as parameter for another generic interface? 是否可以定义T1[T2]是一个数组并将第一个元素的类型作为另一个通用接口的参数?

OK, I figured out that I can use conditional types. 好的,我发现我可以使用条件类型。

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