Find the object in the array that has a name that is a combination of

I am facing an issue in implementing TypeScript validation for filtering an array. I have a specific array of actions and I want to filter out internal actions from it. Despite my efforts, I am unable to properly communicate to TypeScript that the filteredActions array should not contain internalAction anymore.

Below is my attempted solution:

type ActionName = 'replaceText' | 'replaceImage' | 'internalAction';

interface Action {
  name: ActionName
}
const INTERNAL_ACTIONS = ['internalAction'] as const;
type InternalActions = typeof INTERNAL_ACTIONS[number];

const actions: Action[] = [{
   name: 'replaceText'
}, {
   name: 'replaceImage'
}, {
   name: 'internalAction'
}];
const isInternalAction = (name: ActionName): name is Exclude<ActionName, InternalActions> => name in INTERNAL_SLIDE_ACTIONS;
const filteredActions = actions.filter((action) => !isInternalAction(action.name));
for (const action of filteredActions) {
  if (action.name === 'internalAction') {
    // TypeScript error expected here because internalAction shouldn't be present
  }
  if (action.name === 'replaceImage') {
    // No TypeScript error expected here
  }
}

Answer №1

The problem lies within the arrow function isInternalAction.

In TypeScript, to check if an element is present in an array, you should not use the in operator. Instead, consider using methods like includes, some, find, or indexOf.

To improve your code, consider a snippet like:

type ActionName = 'replaceText' | 'replaceImage' | 'internalAction';

interface Action {
  name: ActionName
}
const INTERNAL_ACTIONS: readonly ActionName[] = ['internalAction'] as const;
type InternalActions = typeof INTERNAL_ACTIONS[number];

const actions: Action[] = [{
  name: 'replaceText'
}, {
  name: 'replaceImage'
}, {
  name: 'internalAction'
}];

// Use includes to verify presence in the array
const isInternalAction = (name: ActionName): boolean => INTERNAL_ACTIONS.includes(name);
const filteredActions = actions.filter((action) => !isInternalAction(action.name));

console.log(filteredActions)

You can also test and run this code in a TypeScript playground here.

Answer №2

The key was using the filter method to rebind the action while excluding certain names:

const filteredActions = slide.actions.filter((action): action is Action & {
    name: Exclude<ActionName, InternalActions>
} => typeof INTERNAL_ACTIONS.find(i => i === action.name) === 'undefined');

This ensured that each action maintained the correct typings after filtering.

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

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

Struggling to form an array of arrays: encountering an issue with data.map not being a function

I have received some data in the following format: const mockData = [ { "1": [ { val1: 0.9323809524, val2: 5789.12, val3: 84.467, val4: 189.12, val5: 8, bins: 1, }, { ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...

Guide to executing Jest tests with code coverage for a single file

Instead of seeing coverage reports for all files in the application, I only want to focus on one file that I am currently working on. The overwhelming nature of sifting through a full table of coverage for every file makes it difficult to pinpoint the spe ...

The protractor tool is unable to recognize an Angular component when it is displayed on the page

I have implemented end-to-end (e2e) testing on my project, but I am facing issues that are causing my tests to fail. Below is a snippet of my app.po.ts file: import { browser, by, element } from 'protractor'; export class AppPage { public b ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: The issue arises when setting the div's width as a percentage of the ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Enhance the glowing spinner in a react typescript application

Recently, I transformed an html/css spinner into a react component. However, it seems to be slowing down other client-side processes significantly. You can see the original design on the left and the spinning version on the right in the image below: This ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

Merging pertinent information from separate arrays

Seeking assistance in merging data from two distinct arrays with varying structures. Data is acquired via API, the initial request: [ { "category_id": "12345", "category_name": "itemgroup 1", "cat ...

Migration of Angular dynamic forms project - The error "input" does not have an initializer or a constructor, and another issue with Type T | undefined

Angular dynamic forms project migration - encountering Type T | undefined error In my quest to find a sample project demonstrating the creation of Angular forms using JSON datasets, I stumbled upon this repository: https://github.com/dkreider/advanced-dyn ...

Combining arrays that run parallel in Jquery

Seeking a solution similar to looping through multiple arrays in parallel using jQuery, but this time to construct an HTML page. I have three sets of parallel objects with arrays, potentially forming a 2D array. {"images":["Bellevue\/images\/1. ...

Having trouble integrating jQuery into an Angular CLI project

I'm trying to incorporate jQuery into my angular project created with angular cli. I followed the instructions provided on this website: To begin, I installed jQuery by running: npm install --save jquery; Next, I added type definitions for jQ ...

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this: myData = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined]; The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Angular2 tutorial with VS2015 may encounter a call-signature error that is expected

Currently following the Angular2 tutorial in VS2015 and encountering an issue with a warning that is impeding the compilation of one of my TypeScript files. The link to the tutorial is provided below. https://angular.io/docs/ts/latest/tutorial/toh-pt4.htm ...