Typescript 类型系统的一些更强大的部分允许我们指定此聚合函数的类型安全版本。我详细介绍了一种方法Part 1 below.
当公开这个类型安全的聚合函数时,我们需要执行一些额外的检查,因为 Functions 目前不支持联合类型 https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types(请参阅 Palantir 文档中的“函数 API:输入和输出类型”)。我为此列出了我的代码Part 2 below.
第 1 部分:类型安全聚合
首先,我们列出所有想要分组为新的属性 API 名称联合型 https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types of 文字类型 https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types。这些应该是您通常用来访问函数中这些属性的 API 名称。
type AggregatableStringProperties = "propertyA" | "propertyB" | ...;
现在,我们可以定义一个类型安全的聚合函数,它接受一个对象集以及要聚合的属性(其中的属性)AggregatableStringProperties
):
private async flexibleCounter2DimensionTestImpl(
objects: ObjectSet<Data>,
xaxis: AggregatableStringProperties,
) : Promise<TwoDimensionalAggregation<string>> {
return objects
.groupBy(val => val[xaxis].topValues())
.count();
}
第 2 部分:将其公开为@Function()
使用我们定义的类型安全聚合函数Part 1,我们现在可以使用类型断言 https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions。在下面的代码中,我添加了一些可选逻辑,以为该函数的用户提供有用的调试信息。
@Function()
public async flexibleCounter2DimensionTest(
objects: ObjectSet<Data>,
xaxis : string
): Promise<TwoDimensionalAggregation<string>> {
const xaxis_t = xaxis as AggregatableStringProperties;
if (Data.properties[xaxis_t] === undefined || Data.properties[xaxis_t].baseType.type !== "string") {
throw new UserFacingError("xaxis argument ('" + xaxis + "') is not a string property of the Data object");
}
return this.flexibleCounter2DimensionTestImpl(objects, xaxis_t);
}