Tips for creating a TypeScript function that only needs one property from an object

Looking to overcome the habit of using any in TypeScript, specifically when creating a function that adds or removes an item from an array. The key requirement is that the item must have an id property of type string. Here's how I currently have it implemented:

interface Item {
  id: string;
  [key: string]: any;
}

function toggleArrayItem(array: Item[], item: Item) {
  const index = array.findIndex(i => i.id === item.id);

  if (index >= 0) {
    array.splice(index, 1);
  } else {
    array.push(item);
  }
}

I've considered adjusting the third line to include a list of possible types such as

string | number | string[] | number[]
, but realized this isn't a viable solution. How can I rewrite this function without resorting to using any?

Answer №1

Here's a code snippet that could come in handy:

interface Product {
  code: string;
}

function updateProductList<T extends Product>(productList: T[], product: T){
  const index = productList.findIndex((p) => p.code === product.code);

  if (index >= 0) {
    productList.splice(index, 1);
  } else {
    productList.push(product);
  }
}

const x = {code: 'ABC123', name: 'example'};
const y = {code: 'XYZ456', price: 25};
const z = {code: 'LMN789', price: 15};

updateProductList([] as Product[], x);
updateProductList([y,z], y);

Feel free to test this on TS Playground: https://tsplay.dev/qrTjku

Answer №2

Simply eliminate the [key: string]: any; line if it serves no purpose for you:

interface Product {
  code: string;
}

function modifyProductList(list: Product[], item: Product) {
  const idx = list.findIndex(i => i.code === item.code);

  if (idx >= 0) {
    list.splice(idx, 1);
  } else {
    list.push(item);
  }
}

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 method for verifying that one type extends another in the TypeScript compiler API?

In the process of building a tool (partly to test its functionality), I am developing a way to condense a set of TypeScript definitions into a clean d.ts file, while ignoring unnecessary helper types used for reshaping data. This approach is proving quite ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

What is the best way to retrieve unique elements from a mongoose database based on specific criteria?

In my Node.JS project, I have a model called Activity with certain attributes defined as follows: const Activity = mongoose.Schema({ name: { type: String, require: [true, "A activity must have a name"] }, city: { ...

What is the best method for eliminating a character from all elements in jQuery classes?

I am working on an Angular 4 app where every .inner-page class in a html element includes a "/". For instance: <div _ngcontent-c0="" class="inner-page /login"> <div _ngcontent-c0="" class="inner-page /register"> I need to eliminate the "/" c ...

What are the steps to take in deploying a JavaScript automation application?

After successfully creating a web automation program using Selenium and JavaScript, my goal is to make it accessible to everyone without any dependencies or technical coding knowledge required. I want it to be user-friendly for non-technical individuals. ...

Is there a way to simulate pressing the ENTER/RETURN key using JavaScript executor in Selenium using Python?

Greetings everyone, I am a newcomer to Python Selenium and currently working on automating a website. However, I have encountered an issue with the search text box of the website as it does not feature any clickable buttons once the text is entered. Here ...

Refreshed pages in Next.js often encounter intermittent 503 service unavailable errors with static chunks

Currently working on a static export website in next.js with the following configuration settings. Update: It appears that the 503 errors are related to nginx 503s when serving the files. I can provide the nginx configuration if necessary. const nextConfi ...

What is the tick angle for the dateAxisRenderer in jqplot?

Is it possible to adjust the angle for dateaxis rendering in jqplot specifically for the x-axis? Any help or guidance is appreciated. Below is the relevant code snippet: xaxis: { min:'2009-11-01 00:00&a ...

I encountered an issue while attempting to secure the key with node-redlock, as it results

I need to lock the key called "ProjectData:GSTest" that is currently stored in a redis database. Below is the code I am using to achieve this, but it is throwing an error. Can someone please help me identify what is wrong here? const redlock = new Redlock( ...

session failed to register the third variable

I have successfully implemented a login system in codeigniter. However, I am facing an issue where the session is not storing the user_type variable when I log in. I have reviewed my code multiple times but cannot seem to figure out what is causing this pr ...

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Despite encountering the 'property x does not exist on type y' error for Mongoose, it continues to function properly

When working with Mongoose, I encountered the error TS2339: Property 'highTemp' does not exist on type 'Location' when using dot notation (model.attribute). Interestingly, the code still functions as intended. I found a solution in the ...

JavaScript EasyBitConverter

Looking to create a basic C# BitConverter equivalent in JavaScript, I've developed a simple BitConverter implementation. class MyBitConverter { constructor() {} GetBytes(int) { var b = new Buffer(8); b[0] = int; b ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

Can you show me how to use vuejs to implement h2 tags?

Within the article, there are H2 tags that I want to use as a table of contents. However, despite attempting methods like Replace and substring, I haven't been able to isolate only the H2 tags from the content. The post content is structured in JSON f ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

JavaScript counter that starts at 1 and increments with each rotation

I am working with an array of image IDs. let images = ['238239', '389943', '989238', ... ]; let max = images.length; The array begins at index 0 and its size may vary. For instance, if there are 5 images in the array, the i ...