sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type

interface TypeA {
  attribute1: string
  attribute2: string
}

interface TypeB {
  attribute3: string
  attribute4: string
}

function customFilter(obj: TypeA[] | TypeB[]) {
  if(/*obj belongs to TypeA */) {
    return obj.filter(item => item.attribute1 === 'test')
  }

  if(/*obj belongs to TypeB */) {
    return obj.filter(item => item.attribute3 === 'something')
  }
}

Alternatively, I'm exploring ways to determine the type of array received

Answer №1

An ordinary array by itself does not possess attributes that distinguish its elements' types.

Nevertheless, you have the option to utilize a functional type guard for verifying at runtime whether the elements of the array adhere to the anticipated type. Subsequently, you can safely execute property access operations within the filter callback function:

TS Playground

function arrayItemsHaveProperty<P extends PropertyKey>(
  array: object[],
  prop: P,
): array is Record<P, unknown>[] {
  return array.every((o) => prop in o);
}

interface TypeA {
  attribute1: string;
  attribute2: string;
}

interface TypeB {
  attribute3: string;
  attribute4: string;
}

function fitlerFunc(obj: TypeA[] | TypeB[]) {
  if (arrayItemsHaveProperty(obj, "attribute1")) {
    return obj.filter((item) => item.attribute1 === "test");
    //     ^? (parameter) obj: TypeA[]
  }
  return obj.filter((item) => item.attribute3 === "something");
  //     ^? (parameter) obj: TypeB[]
}

It should be noted that this method prioritizes simpler syntax over performance (resulting in two iterations of the array) — you can achieve it in a single iteration, but type assertions would be necessary. The decision depends on the specifics of your particular usage scenario.

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

Is there a way to implement a function in Javascript or CSS where hovering over a button will cause a div to scroll either left or right

I am working on creating a unique photo gallery layout with a description block positioned below the images. My goal is to incorporate two arrow buttons, one on each side of the photos, that will trigger a scrolling effect when hovered over - shifting the ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

What is the best way to insert hyperlinks within every cell of a table using Angular?

I am currently working on a table created with ng-repeat in Angular. The cells are populated by variables in the scope. <tbody> <tr ng-repeat="item in items" myDirective> <td>{{item.title}}</td> <td>{{item.field}}&l ...

Why does Res.send return an empty object when console.log indicates it is not empty?

I am currently facing a challenge while using the Google Sheets API with Express, as I have limited experience with JavaScript. My goal is to pass a JSON object from Express to React, but for some reason, when I send the object, it appears empty on the fro ...

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

Utilizing an external JavaScript file for developing applications on Facebook

I am looking to incorporate external JavaScript into my Facebook application development. Specifically, I am hoping to utilize the Ajax tab feature in my application. ...

Integrating Asp.Net Core for server-side functionality with React for client-side interactions

I have started a simple Asp.Net default project in Visual Studio 2015 using the template: ASP.NET Core Web Application (.NET Core) / Web Application, No Authentication. Following that, I created a package.json file to load all the necessary packages for R ...

The "isActive" value does not share any properties with the type 'Properties<string | number, string & {}>'. This issue was encountered while using React with TypeScript

I'm attempting to include the isActive parameter inside NavLink of react-router-dom version 5, but I'm encountering two errors. The type '({ isActive }: { isActive: any; }) => { color: string; background: string; }' does not have an ...

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...

Utilize Javascript ES6 to Sort Through Data in a Table

I require assistance with my project using Material UI and React. There are two key implementations that I need: I am looking to create a filtering system for all rows in each column as shown in the attached image. Additionally, I need a button that can a ...

What is the process for adding content to a JSON object?

I may have a simple question, but I'm new to backend development and I'm trying to figure out how to post in JSON format. Here is the JSON schema I am working with: email: { type: String, unique: true, lowercase: true, required ...

What is the best way to organize notifications by dates in a React application?

I'm currently working on a notifications component where I need to sort notifications by dates and then display them. Although I attempted the following code, it didn't work as intended: const result = notifications.notificationRows.sort((a, b) ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Check for support of Symbol.toStringTag in JavaScript

Can this function reliably detect the presence of @@toStringTag in all environments? function hasToStringTagSymbol() { if (Symbol && (typeof Symbol() == "symbol") && !!Symbol.toStringTag) { var xTest = function () { }; xTest.prototyp ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...