In Typescript, develop a tuple type that repeats itself

My API, specifically the Elasticsearch bulk API, requires an array of operations where each operation is a pair. The first element in the pair specifies the operation (index, update, create, delete) and the second element contains the data (excluding delete).

A simplified representation of a single operation would be:

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;

The parameter passed to the API is a flattened array of these tuples - essentially a list of operations and optionally accompanying data.

I'm trying to figure out how to model this type in Typescript. It's not a tuple due to its undetermined length, and it's not an array because the types of elements depend on their position in the array (for example, except for BulkDelete, even indices represent the "operation" while odd ones represent the "operand").

Answer №1

The package @elastic/elasticsearch in NodeJS is known for its strong typing system. It defines the various bulk actions as follows:

type Action = IndexAction | CreateAction | UpdateAction | DeleteAction

Within this framework, the IndexAction structure looks like this:

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

For further details and insights, you can refer to the source code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Encountering difficulties importing a component from a library into my Nx Expo React Native application

Having an issue with my Nx monorepo which contains an Expo React Native app and various libraries. The problem arises when trying to import a component from a library within the application, resulting in Error: Cannot resolve @monorepo/account-manager Wi ...

Autodesk Forge serves as a hub for hosting dependencies on a nearby server

Our company has implemented an Angular/TypeScript version of the Forge Viewer, currently loading dependencies from Autodesk's server. To ensure these files are always accessible to our customers, we want to host them on our own servers. However, attem ...

What is the process for applying cdkDropList to the tbody when using mat-table instead of a traditional HTML table?

I have been experimenting with the mat-table component in my Angular project, following a simple example from the documentation: <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!--- These columns can be ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Determine the Number of Elements in PHP Array

I am struggling with counting my arrays, can someone assist me? Array ( [2014-06-17] => Array ( [0] => Array ( [id] => 40404 [client] => Client 1 ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using this.router.routerState.snapshot['url'] to r ...

Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to: Check for an internet connection; Receive a JSON file from the server and store the data in a file if the server is reachable; Read from the file if the connec ...

Transferring Dataframe from Python to LabVIEW

Is it possible to convert a 1 by 400 array in Python into a dataframe (df) format for sending to LabVIEW? Will LabVIEW be able to receive the array as a dataframe (df)? ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

Error encountered in Azure Pipelines build task: Failure due to requirement for initialization

When I directly invoke index.js using node, everything works fine. However, when running the Mocha tests, the task fails with a "Must initialize" error message. This is how my tasks index.ts code looks like: import * as path from "path"; import tl = requ ...

How can I efficiently map an array based on multiple other arrays in JavaScript/TypeScript using ES6(7) without nested loops?

I am dealing with 2 arrays: const history = [ { type: 'change', old: 1, new: 2 }, { type: 'change', old: 3, new: 4 }, ]; const contents = [ { id: 1, info: 'infor1' }, { id: 2, info: 'infor2' }, { id: ...

The function res.status is not defined

Currently, I am in the process of integrating my upcoming app with Google Sheets. I have relocated the function that manages the post request to "app/api/sheets" as per the recommended documentation. import type { NextApiRequest, NextApiResponse } from &ap ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Combine the individual arrays into a single array

I need a solution to combine all the child arrays into a single, large array. array ( [0] = [0] = '0ARRAY', [1] = '1ARRAY' [1] = [0] = '2ARRAY', [1] = '3ARRAY' ) result ...

Is Swift affected by the same 2GB maximum serialization size issue as Java?

In programming languages like Java and other JVM based languages, it is common to serialize data into an array of bytes, especially when needing to send information over a network. But how does Swift handle data serialization for network communication? An ...

The parameter cannot be assigned to type 'HTMLCanvasElement | null' due to conflicting arguments

I am encountering an issue with the following code, as it fails to compile: import React, {useEffect} from 'react' import {Card, Image} from 'semantic-ui-react' import * as chart from 'chart.js' export const PieChartCard = ...

Efficiently transforming a nested object array into a single dynamic array

// I have a collection of various objects _id: "5e5d00337c5e6a0444d00304" orderID: 10355 orderDate: "2020-03-02" user: _id: "5e2e9699a648c53154f41025" name: "xyz1" email: "<a href="/cdn-cgi/l/email-protection" class="_ ...

how to retain the state value as a number and enable decimal input in a TextField component in React

Currently working on a project using React, Material UI, and TypeScript. I need to enable decimal values in a TextField while ensuring that my state value remains a number type instead of a string. export default function BasicTextFields() { const [value ...