簡體   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