Creating a Proxy for an Array in TypeScript: A Step-by-Step Guide

When attempting to utilize a Proxy for adding logic whenever a value in my array is set to a new value, I encountered an issue with TypeScript. The error arises from the fact that TypeScript does not support indexing an array with anything other than a number.

const nums = [1, 2, 3, 4, 5];

const handler: ProxyHandler<number[]> = {
  set(target: number[], property: string | symbol, newValue: any) {
    target[property] = newValue;
    return true;
  },
};

const proxy = new Proxy(nums, handler);

Specifically, I am receiving the error

Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)
when trying to assign a new value with target[property] = newValue;.

I am now seeking advice on how to resolve this issue and make TypeScript happy. Any suggestions or solutions would be greatly appreciated.

Answer №1

Are arrays indexed with strings? No, arrays are generally indexed with numbers, as indicated by TypeScript.

const numbers = [1, 2, 3, 4, 5];

const arrayHandler: ProxyHandler<number[]> = {
  set(target: number[], property: string | symbol | number, newValue: any) {
    if (typeof property !== 'number') throw new Error('You can only index an array with a `number`!')
    target[property] = newValue;
    return true;
  },
};

const proxyArray = new Proxy(numbers, arrayHandler);

Playground Link

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

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Compare an integer variable with numbers that have been previously saved in an array

Just dipping my toes into the world of coding, I have basic skills in Java and am eager to learn more on my own and from others. Not currently enrolled in university. Hey there! I'm attempting to create an array with a small capacity (5 integers) to ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...

The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure: my-package |- index.js |- index.d.ts |- package.json The index.d.ts file includes global declarations like: declare ...

Issue with updating Class Module type array

Recently, I encountered a perplexing issue with arrays where I could assign values to the entire array but not to individual elements. This scenario occurred within a data class module called Class_E. Public Name As Variant Public Age As Variant ...

Issue with React TypeScript: Only the first state update takes effect, despite multiple updates being made

Check out this sandbox I created here. When you leave any of the form inputs blank, I should be seeing 3 errors but instead, I only get one. Can anyone explain why this is happening? import React, { ChangeEvent, useState } from 'react'; import { ...

applying multiple angular filters on table column values

I'm currently facing a challenge with implementing a filter pipe that can handle multiple values across multiple attributes in a table. While I have successfully managed to filter multiple values on a single attribute, I am struggling to achieve the ...

Issue when rendering <options> while looping through country object in the country list

To retrieve a list of all countries in my React project written in TypeScript, I am utilizing the countries-list library which can be found here. My intention is to create a <Form> that includes a <Select> dropdown menu populated with the coun ...

Eslint is unable to locate file paths when it comes to Solid.js tsx extensions

Whenever I attempt to import TSX components (without the extension), Eslint raises an error stating that it's unable to resolve the path: https://i.sstatic.net/NiJyU.png However, if I add the TSX extension, it then prompts me to remove it: https:// ...

When attempting to publish an index.d.ts file using npm, the module is

We are currently in the process of developing an npm package that will serve as the foundation for most of our projects. However, we have encountered some issues that need to be addressed: The index.d.ts file of our base npm package is structured as shown ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...

Grabbing specific inline JSON data with jQuery's .getJSON function or a comparable method

I am trying to extract information from an array embedded within a <script> tag using jQuery's .getJSON method. According to the documentation I've come across (http://api.jquery.com/jquery.getjson/), .getJSON typically needs a URL and an e ...

Tips for fixing the issue of 'expect(onClick).toHaveBeenCalled();' error

Having trouble testing the click on 2 subcomponents within my React component. Does anyone have a solution? <Container> <Checkbox data-testid='Checkbox' checked={checked} disabled={disabled} onClick={handl ...

Monitor and compile numerous directories simultaneously in TypeScript (monorepo)

I've been searching far and wide online for a solution to my problem, but unfortunately, I haven't come across anything useful yet. Essentially, I am in need of a tool or method that will allow me to kick off TypeScript file Watching/Compiling in ...

Using TypeScript's generic rest parameters to form a union return type

Right now, in TypeScript you can define dynamic generic parameters. function bind<U extends any[]>(...args: U); However, is it possible for a function to return a union of argument types? For example: function bind<U extends any[]>(...args: ...

Loop through each object and add them to an array in a file using NodeJS

Currently, I have a scenario where I am executing a POST request inside a for loop function and the response needs to be stored as an object in an array file. Below is the code snippet that I am utilizing: var arrayFile = fs.createWriteStream("arrayFile.j ...

Transforming an array of Instagram photos into an array specifically consisting of chosen photos

Trying to configure my Instagram API website to allow users to pick photos. I have managed to store the data in a database and display the photos, but I'm struggling to enable photo selection in a different array. Below is the code snippet: <?ph ...

It's conceivable that the item is 'null'

I am encountering Typescript errors in my code that are related to parameters I am receiving from a previous screen. This is similar to the example shown in the React Navigation documentation found at https://reactnavigation.org/docs/params/. interface Pix ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

Showing a JSON array response on a TextView without including the array name

Is it possible to transfer JSONArray without specifying a JSON name? [{ "points": 411, "type": "C" }, { "points": 1600, "type": "G" }, { "points": 13540, "type": "I" }] The points need to be displayed on 3 separate TextViews, not ...