Access Element in Array by Type using TypeScript

Within a TypeScript project, there exists an array of containers that possess a type attribute along with supplementary data based on their individual types.

type Container<Type extends string> = {
    type: Type;
}

type AContainer = Container<"a"> & {
    dataA: number;
}

type BContainer = Container<"b"> & {
    dataB: boolean;
}

const data: (AContainer | BContainer)[] = [
    { type: "a", dataA: 17 },
    { type: "b", dataB: true }
];

The objective is to formulate a function that will permit the selection of an element from the aforementioned array by its designated type while maintaining full adherence to type safety. An example implementation might look like this:

const getByType = <T extends string>(data: Container<string>[], type: T): Container<T> => {
    for (const c of data) {
        if (c.type === type) return c;
    }
    throw new Error(`No element of type ${type} found.`);
};

const dataA: AContainer = getByType(data, "a");

The complication arises in persuading TypeScript that the function adheres to strict type-safety guidelines and conclusively returns an element of the original array aligned with the requested type.

A potential solution has been attempted as depicted below:

const getByType = <ContainerType extends Container<string>, Type extends string>(data: (ContainerType & Container<string>)[], type: Type): ContainerType & Container<Type> => {
for (const c of data) {
    if (c.type === type) return c;
}
throw new Error(`No element of type ${type} found.`);
};

However, TypeScript encounters difficulty in comprehending that the comparison 'c.type === type' substantiates a transformation from a Container<string> structure into a Container<Type>. Furthermore, it struggles to recognize that the return type derived from an exemplary call such as '

AContainer | (Container<"b"> & { dataB: boolean; } & Container<"a">)
' should ideally equate to AContainer despite the clash between Container<"b"> and Container<"a">.

A feasible workaround involves leveraging a type predicate akin to the one represented below which can resolve the initial concern but falls short in addressing the subsequent issue:

const isContainer = (c: Container<string>, type: Type): c is Container<Type> => {
return typeof c === "object" && c.type === type;
};

Is there a viable methodology to rectify this predicament? Ideally, both the implementation of getByType itself and its utilization should exhibit rigorous adherence to type-safety principles. In scenarios where absolute compliance may not be attainable, the preference lies in ensuring that invoking getByType does not necessitate any compromises through unsafe type assertions.

The definitions pertaining to the container types can be modified, although the factual data remains immutable. This setup originates from interactions with the xml2js XML parsing framework.

Answer №1

To achieve our objective, we can make use of the infer and Extract methods. Here is an example:

const getByType = <ContainerType extends Container<string>, Type extends ContainerType extends Container<infer T> ? T : never, Chosen extends Type>(data: ContainerType[], type: Chosen) => {
    for (const c of data) {
        if (c.type === type) return c as Extract<ContainerType, {type: Chosen}>;
    }
    throw new Error(`No element of type ${type} found.`);
};

const containerA: AContainer = {
  dataA: 1,
  type: "a"
} 
const containerB: BContainer = {
  dataB: true,
  type: "b"
}
const b = getByType([containerB, containerA], 'b')
// The inferred type of b is BContainer 

Key points to note:

  • type: ContainerType extends Container<infer T> ? T : never
    specifies that the argument must contain a specific type from the given array
  • Extract<ContainerType, {type: Chosen}>
    indicates that we are returning an element of the union with the exact type specified by {type: Chosen}

Additionally, there is strict typing enforced on the second argument, in this case narrowed down to a | b

Playground

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: Module '...' or its type declarations could not be located

Recently, I attempted to deploy my next.js app on Vercel, only to encounter an error that read: "Type error: cannot find module '...' or its corresponding type declarations." After some investigation, I suspect this error is related to local modu ...

Issue with routing in Angular 6 is caused by the "#" character

I am currently working on an Angular 6 project. In my app.routes, I have set it up like this. However, I am facing an issue where I can only access the route using localhost:4200/#/Student instead of localhost:4200/Student. Can you help me identify where t ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Is it necessary to verify the apiKey or does the authentication of the user suffice for an HTTPS callable function?

I'm interested in creating a cloud function that can be executed from both the client and the backend. After exploring the documentation, I learned that an HTTPS callable function will automatically include user authentication data, accessible through ...

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Guide on creating a custom command within the declaration of Tiptap while extending an existing extension with TypeScript

I'm currently working on extending a table extension from tiptap and incorporating an additional command. declare module '@tiptap/core' { interface Commands<ReturnType> { table: { setTableClassName: () => ReturnType; ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

Utilizing Express JS: Invoking a function within my class during routing operations

Currently, I am in the process of developing a MERN Application using Typescript. I seem to be encountering an issue with this within my class. When utilizing this code snippet: router.post("/create", user.createNewUser); It becomes impossible ...

Can you explain the distinction between using tsserver and eslint for linting code?

As I work on setting up my Neovim's Native LSP environment, a question has arisen regarding JS/TS linter. Could someone explain the distinction between tsserver and eslint as linters? I understand that tsserver is a language server offering features ...

Receiving the error notification from a 400 Bad Request

I'm having trouble showing the errors returned from an API on my Sign up form when a user submits invalid data. You can check out the error response in the console here: console ss This is my approach in RegisterComponent.ts: onSubmit() { this.u ...

Unexpected token in catch clause in React Native TypeScript

Despite having a fully configured React Native Typescript project that is functioning as expected, I have encountered a peculiar issue: Within all of my catch blocks, due to the strict mode being enabled, typescript errors are appearing like this one: htt ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Optimizing performance in React: A guide to utilizing the Context and useCallback API in child

Utilizing the Context API, I am fetching categories from an API to be used across multiple components. Given this requirement, it makes sense to leverage context for managing this data. In one of the child components, the categories can be expanded using ...