Union types can be used to constrain generic type parameters in Typescript

I'm working on a function

 uniqueIds(first: any[], second: any[]): number[] {
        let prop = first[0] instanceof Owner ? "OwnerId"
            : "BankId";
        return _.unique(
            _.map(
                first,
                o => o[prop]
            )
            .concat(
                _.map(
                    second,
                    o => o[prop]
                )
            )
        ).filter(o => o);
    }

This function is specifically designed to work with either Bank or Owner types, and nothing else. These two types do not share any interface or inheritance chain.
My current implementation might not be the most elegant solution for this scenario. Is there a better way to achieve something like

uniqueIds<T> where T Bank | Owner
without having to stick with my current approach?

Answer №1

If you want to declare a function that accepts either Owner[] or Bank[], you can define it as follows:

function findUniqueIds<T extends Owner[] | Bank[]>(first: T, second: T) { ... }

However, TypeScript may raise a noImplicitAny error because it cannot verify that o[prop] is always a number. To address this, consider passing the property name along with the arrays:

function findUniqueIds<K extends string, T extends {[P in K]: number}>(
    prop: K, first: T[], second: T[]): number[] {
    return _.unique(
        _.map(
            first,
            o => o[prop]
        )
        .concat(
            _.map(
                second,
                o => o[prop]
            )
        )
    ).filter(o => o);
}

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

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Differences between Angular components and TypeScript classes in models

In my observation, I have noticed that in several instances, manual models are being created for components to specifically manage the data. Despite this, the component already contains a ts class along with the html and css data. Shouldn't the task ...

Angular is failing to show any data on the display, despite there being no apparent errors

As a newcomer to Java and Angular, I am currently enrolled in a course on getting started with Angular. I have been attempting to display information in the navigator, but for some reason, nothing is showing up. Despite thoroughly checking my code, I could ...

Utilize the index of a for loop to manipulate an Angular string

When working with different objects and creating forms simultaneously, I've come across a challenge. My initial idea for handling the submission was to use the following code: <form (ngSubmit)="submitForm{{u}}()"> However, incorporating the in ...

Dealing with code in Angular when transitioning to a different component

I have an Angular component that displays data and includes a button called "Go to Dashboard". I want to implement a feature where the user can either click on this button to navigate to the dashboard or have the application automatically redirect them aft ...

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Zod: ensure at least one field meets the necessary criteria

Currently, I am in the process of developing a form that allows users to input either their email address or phone number. While they have the option to provide both, they are required to enter both before proceeding. For this project, I am utilizing Zod a ...

Adding properties to request object on-the-fly - Google Pay [Typescript]

Here is how I am constructing the payment request object: paymentRequestObject: google.payments.api.PaymentDataRequest = { apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [ { type: 'CARD', parameters: { allowedAuthMethod ...

A step-by-step guide on importing stompjs with rollup

My ng2 app with TypeScript utilizes stompjs successfully, but encounters issues when rollup is implemented. The import statement used is: import {Stomp} from "stompjs" However, upon running rollup, the error "EXCEPTION: Stomp is not defined" is thrown. ...

Steps to eliminate the typescript template from create-react-app

Initially, I decided to incorporate TypeScript into my React project, which led me to run the command npx create-react-app my-app --template typescript. However, now I'm looking for a way to revert back and remove TypeScript from my setup. Is there a ...

Troubleshooting and setting breakpoints in TypeScript code for Angular Web applications using the Firefox browser

Is there a method to add breakpoints to .typescript source files in my Angular application with Firefox Developer Tools? While I am able to add breakpoints to the generated javascript files, is it possible to debug the .ts source files directly? This quer ...

Steps for incorporating ProxyConfig in Angular7 Application1. First, create a new

Having trouble building the application with proxy configuration. It works fine with ng serve or npm run start, but I need it to work with npm run build or ng build. After that, I want to deploy the dist folder to Tomcat webapps and make everything functio ...

Tips for evaluating the stickiness of a block within a cell when it adheres to a mat-header-cell

I am working with an Angular table and facing an issue. How can I make the span element in the cells of the first column stick to the sticky mat-header-row when scrolling down the table? My requirement is for the span element to stay attached to the lower ...

Error message: Missing "@nestjs/platform-express" package when performing end-to-end testing on NestJS using Fastify

Just set up a new NestJS application using Fastify. While attempting to run npm run test:e2e, I encountered the following error message: [Nest] 14894 - 11/19/2021, 10:29:10 PM [ExceptionHandler] The "@nestjs/platform-express" package is missi ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Error: Failed to load chunk 552 due to chunk loading issue

Currently in the process of migrating Angular 12 to version 13. The migration itself was successful, however, upon running the project in the browser post a successful build, the application fails to display. On checking the console, I encountered the foll ...