typescript - 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.
解决方案
假设您的“特定类型”是您提供的类型,返回 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
检查“用户定义的类型保护”。队友的欢呼声。
推荐阅读
- git - 重新基于特定的提交
- algorithm - 矩阵乘法算法时间/空间复杂度
- javascript - 根据状态更改对象中的元素
- c++ - 比较器返回在 C++ 中的真正含义是什么
- javascript - 返回时,如何获取之前的输入值
- kubernetes-helm - 如何安装 grafana 插件?
- sql - 合并添加额外字符
- amazon-web-services - 使用 AWS CLI 将 Windows 实例上的文件同步到 AWS S3 存储桶并删除旧文件(无需存储网关或 FSx)
- routes - 如何使用 Veins、SUMO 和 Omnet++ 更改“changeVehicleRoute”功能?
- postgresql - “autovacuum”和“COMMIT”始终是加载 RDS postgresql 性能洞察力的主要贡献者是否正常?