【问题标题】:Create repeating tuple type in Typescript在 Typescript 中创建重复元组类型
【发布时间】:2021-02-23 16:19:21
【问题描述】:

我有一个 API(弹性搜索批量 API),它接受一组操作,这些操作基本上是对,其中第一个元素是指定操作(索引、更新、创建、删除)的对象,第二个是数据(不是在删除的情况下)。

单个操作可以输入为(简化):

type BulkUpdate = [{ update: { _index: string, _id: string } }, { doc: object }];
type BulkIndex = [{ index: { _index: string, _id?: string } }, object];
type BulkDelete = [{ delete: { _index: string, _id: string } }];
type BulkOperation = BulkUpdate | BulkIndex | BulkDelete;

然后,整个参数是上述元组的扁平数组 - 操作列表和可选数据。

如何在 Typescript 中为这种类型建模?它不是元组,因为它具有不确定的长度,也不是数组,因为元素类型取决于它们的索引(例如,除了 BulkDelete,偶数索引包含“操作”,而奇数索引包含“操作数”)。

【问题讨论】:

    标签: arrays typescript elasticsearch tuples


    【解决方案1】:

    强类型的 NodeJS 包 @elastic/elasticsearch 声明了 bulk 操作,如下所示:

    type Action = IndexAction | CreateAction | UpdateAction | DeleteAction

    IndexAction 在哪里

    interface IndexAction {
      index: {
        _index: string
        [key: string]: any
      }
    }
    

    等等。

    Check the source 寻求灵感。

    【讨论】:

    • 谢谢,但是它模拟了构成参数的单个“元组”(就像我上面创建的类型),但它没有回答如何键入由一个或多个组成的可变长度数组这些元组。
    • 你能进一步澄清一下吗?您尝试为其指定类型的 JSON 是什么?
    • JSON 将是(例如): [ {update:{...},{doc: {...}}, {index:{...},{... }, ... ] IE,可变数量的 TS 元组的串联
    猜你喜欢
    • 2014-06-03
    • 2020-01-29
    • 2022-01-16
    • 2016-05-28
    • 2022-12-18
    • 2023-01-20
    • 2019-09-20
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多