【问题标题】:Generic constraint on multiple type variables多类型变量的通用约束
【发布时间】:2019-05-14 17:52:09
【问题描述】:

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

我有第一个界面

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

第二个使用前一个并且也有 2 个类型变量:

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 的错误:Type 'ObjectContainingArray[KeyOfPropertyWithArray]' does not satisfy the constraint 'any[]'.

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

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

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

    type FirstArrayElement<ElementsArrayType> = ElementsArrayType extends any[] ? ElementsArrayType[0] : never;
    
    interface OuterInterface<
      ObjectContainingArray,
      KeyOfPropertyWithArray extends keyof ObjectContainingArray
    > {
      nestedProperty: GenericInterfaceWithArray<FirstArrayElement<ObjectContainingArray[KeyOfPropertyWithArray]>>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多