【发布时间】:2019-09-27 08:16:28
【问题描述】:
我正在尝试实现一个函数,它将由不同元素组成的数组拆分为特定类型的元素数组(在函数调用中指定)。这是简化的代码:
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);
}
这会导致错误,因为并非ElementType 中的每个元素都与返回类型T 匹配。我将如何实现正确键入的此功能?
这是一个Playground 链接。
另一个使用泛型类型的Playground link。
【问题讨论】:
标签: typescript typescript-typings