如何在Foundry Functions中拥有灵活的分组列?

2024-05-18

在我的 Workshop 应用程序中,我想要一个带有可更改 x 轴的条形图。下拉小部件将用于选择所需的 x 轴。

为此,我正在编写一个 TypeScript 函数,它将返回为图表小部件提供数据的数据。

我写了以下函数:

@Function()
public async flexibleCounter2DimensionTest(
    objects: ObjectSet<Data>,
    xaxis : string ): Promise<TwoDimensionalAggregation<string>> {
    return objects
            .groupBy(val => val[xaxis].topValues())
            .count()
}

The xaxis参数将定义要对其执行分组的列名称。

我在 Foundry Functions 中努力做到这一点,我总是在编译时收到以下错误:

{ "stdout": "src/hospital_provider_analysis.ts(170,9): 错误 TS2322: 类型 'TwoDimensionalAggregation' 不可分配给类型 'TwoDimensionalAggregation'。\n 类型 'BucketKey' 不可分配可分配给类型“string”。\n 类型“false”不可分配给类型“string”。\nsrc/hospital_provider_analysis.ts(171,33):错误 TS7053:元素隐式具有“any”类型,因为类型“的表达式” string' 不能用于索引类型 'BucketableProperties'。\n 在类型 'BucketableProperties' 上找不到参数为 'string' 类型的索引签名。\n", “标准错误”:“” }

有什么想法如何解决这个问题吗?


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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Foundry Functions中拥有灵活的分组列? 的相关文章

随机推荐