首页 > 解决方案 > How to I specify a method filtering an array for a certain type of element?

问题描述

I'm trying to implement a function which splits an array consisting of different elements into an array of elements of a certain type (specified in the function call). This is the simplified code:

export enum GenericElementType {
  ONE = 'type one',
  TWO = 'type two'
}

export interface TypeA {
  id: string;
  type: GenericElementType.ONE;
}

export interface TypeB {
  id: string;
  type: GenericElementType.TWO;
}

export type ElementType = TypeA | TypeB;
const arrayOfElements: (DFDElementType)[] = [];

function filterElementsOfCertainType<T extends ElementType>
  (elements: (ElementType)[], type: GenericElementType): T[] {
  return elements.filter((element: ElementType) => element.genericType === type);
}

This results in an error, because not every element in ElementType matches the return type T. How would I go about implementing this function correctly typed?

Here is a Playground link.

Another Playground link using generic typing.

标签: typescripttypescript-typings

解决方案


假设您的“特定类型”是您提供的类型,返回 ElementType[],并将 element.type 与类型进行比较。认为这应该有效。干杯

编辑:

我想你应该考虑一下模式。从你的最后一个游乐场。elementOfTypeA: TypeA[] 应该是 elementOfTypeA: ElementType[],你已经给出了所需的类型作为参数。用更简单的逻辑来说,这永远不会奏效:

interface  person{
  id: string;
}
type teacher = person | number;

const randomVariable: person = 3;

虽然,这将:

interface  person{
  id: string;
}
type teacher = person | number;

const randomVariable: teacher = 3;

最后一招:

function filterElementsOfCertainType<T extends ElementType>
  (elements: any[], type: GenericElementType): T[] {
  return elements.filter((element: T) => element.type !== undefined && element.type === type);
}

然后 const elementOfTypeA: TypeA[] = filterElementsOfCertainType([a, b, c], GenericElementType.TWO); 将工作。

这似乎也是打字稿文档希望您这样做的方式。 https://www.typescriptlang.org/docs/handbook/advanced-types.html

检查“用户定义的类型保护”。队友的欢呼声。

操场


推荐阅读