Indexing types unexpectedly behaving and generating errors that were not anticipated

I find the code below quite strange...

export class Collection {
    private data: {[k: string]: any} = {};
    constructor () {
        // This part works fine
        this.data["hello"] = "hello";

        // Unexpectedly works
        this.data[2] = 2;
    }
}
export class Collection2 {
    private data: {[k: symbol]: any} = {};
    constructor () {
        // Doesn't work as expected
        this.data["hello"] = "hello";

        // Unexpectedly doesn't work
        this.data[Symbol.iterator] = function () {}
    }
}

Setting the index signature to string should only allow strings to index it, right? Similarly, with symbols. However, numbers can index [k: string] and attempting to use symbol as an index signature results in an error.

Answer №1

It may seem strange at first, but this behavior is actually quite normal. According to the documentation:

When defining an index signature in TypeScript, the parameter type must be either 'string' or 'number'. This is because in JavaScript, you can access object properties using either strings (object["key"]) or numbers (object[0]), so keyof T will be string | number for types with a string index signature.

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

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

React's Material-UI ToggleButtonGroup offers a seamless way

I'm having trouble getting the ToggleButton selected property from material ui to function properly with ToggleButton. I followed the Material Ui documentation and created a StyledToggleButton as shown below: const StyledToggleButton = withStyles({ ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Utilizing TypeScript union types in React: A step-by-step guide

I'm currently working on applying types to ReactJS props using an interface that includes a union type. In the example below, you can see that the tags type is a union type. export interface TagInterface { id: number; name: string; } export inter ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Using custom properties from the Material-UI theme object with custom props in Emotion styled components: a step-by-step guide

I have implemented a custom object called fTokens into the MUI theme using Module augmentation in TypeScript This is how my theme.d.ts file is structured declare module "@mui/material/styles" { interface FPalette { ... } interface FTokens ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Tips for utilizing a ternary operator to set a className in an element

I'm in the process of developing a website using React and Next.js. One of the components on my site is section.tsx, which displays a subsection of an article based on the provided props. I'm looking to add an 'align' property to this c ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

What steps can I take to ensure my dynamic route functions correctly in NextJs?

// /home/[storeId]/layout.tsx import prismadb from "@/lib/prismadb"; import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function DashboardLayout({ children, params, ...

What is causing the issue in locating the assert package for VS Code and TypeScript?

My main issue lies with the pre-installed node libraries (path, fs, assert). Let me outline the process that leads to this problem: Begin by launching Visual Studio. Select File > Open Folder, then pick the root core-demo folder. In the file panel, loc ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Troubleshooting font color issues with PrimeNG charts in Angular

I have a chart and I am looking to modify the color of the labels https://i.sstatic.net/vsw6x.png The gray labels on the chart need to be changed to white for better readability Here is my code snippet: HTML5: <div class="box-result"> ...

Utilizing Angular 2 to retrieve and assign object properties provided by a service to a local variable within a

My video service: public getExercise(exerciseId): Observable<Exercise[]>{ let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers, withCredentials: t ...

Adjusting the angular routerLink based on an observable

When working with HTML in Angular, I am looking for a way to use an <a> tag that adjusts its routerlink based on whether or not a user is logged in. Is it possible to achieve this functionality within a single tag? <a *ngIf="!(accountService ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...

Errors arose due to the deployment of TypeScript decorators

Using TypeScript in a brand new ASP.NET Core project has brought some challenges. We are actively incorporating decorators into our codebase. However, this integration is causing numerous errors to appear in the output of VS2015: Error TS1219 Experim ...

refresh my graph on the user interface once the service responds with JSON data

After obtaining the object successfully from my API, I have already displayed my custom graph component with default values. However, I need to update the 'chart1Title' of the graph component with the value of 'title' from the object. ...