Creating a shared function using TypeScript

Having a vue3 component that displays a list of items and includes a function to delete an item raises a concern about checking parameters and specifying the array for the filter operation. The goal is to create a universal function using typescript.

<template>
  <div v-for="cat in items.cats" :key="cat.id" :style="{ display: ' flex' }">
    <div>{{ cat }}</div>
    <button type="button" @click="deleteItem('cats', cat.id)">delete</button>
  </div>

  <div v-for="car in items.cars" :key="car.id" :style="{ display: ' flex' }">
    <div @delete="deleteItem('cars', car.id)">{{ car }}</div>
    <button type="button" @click="deleteItem('cars', car.id)">delete</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

interface Common {
  id: number;
}

interface Cat extends Common {
  name: string;
  type: string;
}

interface Car extends Common {
  model: string;
  serial: string;
}

interface Item {
  cats: Cat[];
  cars: Car[];
  anotherArray: [];
  oneMoreArray: [];
  oneKey: string;
}

const items = ref<Item>({
  cats: [
    {
      id: 0,
      name: 'Kitty',
      type: 'home',
    },
    {
      id: 1,
      name: 'Sherhan',
      type: 'jungle',
    },
  ],

  cars: [
    {
      id: 0,
      model: 'BMW',
      serial: 'X5',
    },
    {
      id: 1,
      model: 'Audi',
      serial: 'Q5',
    },
  ],

  anotherArray: [],
  oneMoreArray: [],
  oneKey: '',
});

function deleteItem(name?: 'cats' | 'cars', id?: number) {
  if (id !== undefined && name === 'cats') {
    items.value.cats = items.value.cats?.filter((cat: Cat) => cat.id !== id);
  }

  if (id !== undefined && name === 'cars') {
    items.value.cars = items.value.cars?.filter((car: Car) => car.id !== id);
  }
}
</script>



Presenting this solution, utilizing keyof Item

<script setup lang="ts">
function myFunc<T>(entity: keyof Item, id?: number) {
  if (id) {
    (items.value[entity] as T[]) = (items.value[entity] as T[]).filter((item: Common) => item.id !== id);
  }
} // Here, an error occurs: No overload matches this call.
</script>


<template>
  <div v-for="cat in items.cats" :key="cat.id" :style="{ display: ' flex' }">
    <div>{{ cat }}</div>
    <button type="button" @click="deleteItem < Cat > ('cats', cat.id)">delete</button>
  </div>

  <div v-for="car in items.cars" :key="car.id" :style="{ display: ' flex' }">
    <div>{{ car }}</div>
    <button type="button" @click="deleteItem < Car > ('cars', car.id)">delete</button>
  </div>
</template>

A more sophisticated TypeScript solution is essential for enhancing the functionality

Answer №1

The primary issue at hand is that the variable oneKey is declared as a string, while all other attributes are of type array. This is why the code (items.value[entity] as T[]) cannot be executed successfully. Not everything in this scenario is an array. By segregating oneKey into a distinct type, the following solution can be implemented:

const removeItems = (item: Item, label: keyof Item, id: Common['id']): Item => ({
  ...items,
  [label]: items[label].filter((data: Common) => data.id !== id),
});

It is always advisable to prioritize immutability. This approach maintains the purity of the removeItems function, allowing for the reassignment of the output values.

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

comparing values in an array with jquery

I am attempting to retrieve the phone number and mobile number from an array using jquery. jQuery: var data = $('#PhoneLabel').text(); var array = data.split(', '); $.grep(array, function (item, index) { if (item.charAt(0) === &ap ...

How can I retrieve the body from a GET request using Express?

Every time I attempt to execute my code, it returns an error message indicating invalid text. app.post("/charge", (req, res) => { console.log(req.body) }) ...

Fixing a Dropdown Problem in Codeigniter

I have encountered a problem with the Dropdown pop-up feature. Specifically, when I click on the "Add New" option in the Dropdown, the pop-up window fails to open. Here is the code for the Dropdown: echo form_dropdown('Birth_Certificate_Storage_id[& ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

Converting a JSON object that is created dynamically to XML in node.js

Is there a way to convert a dynamically created JSON object into XML using node.js? I am tasked with generating JSON objects dynamically based on available data, which includes nested lists of objects. var Obj = { root: { Door_Keeper: { ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

Despite the value being true, the if statement does not work when used with a Mongoose object in Node.js

Currently working on a bidding app, Below is the schema for the bidding model const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, location: String, specilization: String, image: String, ...

Tips for accessing slot properties within the created lifecycle hook

I am facing an issue with accessing properties that I pass to my slot, as my slotProps are returning undefined. Despite carefully reading the Vue docs and being new to Vue, I am unable to understand why I am unable to access the props data. The Issue Wh ...

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...

What is the best way to incorporate an apostrophe into a string so that it can be displayed in a tooltip using jQuery

There is a text or string stored inside the 'data' variable, containing some texts with apostrophes. The issue I'm facing is that the tool tip is not displaying the text after the apostrophe symbol. How can I include all texts, including apo ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Manipulate a JSON object with JavaScript

Struggling to find a solution on my own. In my hidden field, I have some JSON data stored. To retrieve this data, I'm using the following syntax: $(document).ready(function() { var data = $("#result").text(); var j = JSON.parse(data); j.my_item.to ...

Sprockets could not locate the file for jquery.atwho

I have been attempting to integrate the jquery-atwho-rails into my application, a Rails gem designed for at.js. I have followed all the steps provided, executed bundle install, included the necessary code in both application.js and application.css, stopped ...

Tips for ensuring Node.js waits for a response from a substantial request

When uploading a large number of files, the process can take several minutes. I am currently using a multi-part form to post the files and then waiting for a response from the POST request. However, I am facing issues with timeouts and re-posting of files ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

Securing data in AngularJS $http.post requests: Best practices

While working on $http.post requests for my app's backend, I noticed a security issue. When inspecting the data using tools like firebug in Firefox, I can see all the information being sent. Is it possible for third parties to intercept this data? Th ...

Transfer the html div element to the ajax request

My server-side code runs multiple bigquery queries and organizes the results in a table. The client calls this code via an ajax request. I want to send the table/div generated by the server-side code to the client so that it can be rendered there. Is this ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...

Retrieving Progress Updates from a PHP Script Using XMLHttpRequest

I am currently using JavaScript to execute an XMLHttpRequest to a PHP script that returns data. My goal is to display a progress bar for the user instead of a spinning circle, indicating the progress of fetching and receiving the data. While I understand t ...

AngularJS: iterating through POST requests and passing each index into its corresponding response

Using AngularJS, I am attempting to execute multiple http POST requests and create an object of successfully finished requests. Here is a sample code snippet: var params = [1, 2, 3], url, i, done = {}; for (i in params) { url = '/dir ...