Number as the Key in Typescript Record<number, string> is allowed

As a newcomer to TypeScript, I am still learning a lot and came across this code snippet that involves the Record utility types, which is quite perplexing for me.

The code functions correctly in the playground environment.

const data = async (name: string, id: number): Promise<Record<number,string>> => {
  const obj = {
    foo: 'bar', //I'm confused why this works even though it's 'number'
  }
  return obj
}

However, the following code does not work (2nd line).

const foo1: Record<string, string> = { foo: 'bar' }
const foo2: Record<number, string> = { foo: 'bar' }

I am unsure about the correct type of data that should be used for the 'key'. Feel free to experiment on TypeScript Playground.

Answer №1

The reason for this is because TypeScript needs to be compatible with JavaScript.

Take a look at this simple JavaScript code:

const foo={
  0:42
}

const x = foo['0'] // number
const y = foo[0] // number

As you can see, in JS you can use both string and number keys for the value 0: 42.

Refer to the documentation for both JS and TS:

JS Explanation

Property names Property names are strings or Symbols. Any other value, including numbers, will be converted into a string. This results in 'value', as 1 is converted to '1'.

TS Explanation

Both types of indexers can be supported, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript actually converts it to a string before indexing an object. Therefore, indexing with 100 (a number) is equivalent to indexing with "100" (a string), so they need to match.

But why is this? And what data type should be used for the 'key'?

TypeScript has a built-in type for keys:

type PropertyKey = string | number | symbol

You can utilize PropertyKey without having to declare it separately, as it's already included.

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

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

Unable to add data to an Array once subscribed to BehaviorSubject

Hello everyone, this is my first time asking a question here. I hope it's clear enough for you to understand :) Let's dive straight into the issue at hand. I have a query regarding a behaviorSubject variable in TypeScript that is not allowing me ...

How can I access a file uploaded using dxFileUploader?

I am facing an issue with retrieving a file from dxFileUploader (DevExpress) and not being able to read it in the code behind. The file is only appearing as an object. Here is My FileUploader : { location: "before", ...

Testing an asynchronous function in JavaScript can lead to the error message: "Have you neglected to utilize await?"

Here is an example of the code I am working with: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } = respon; myStatus = statusCode ...

Issue encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

The error message states that the type '{}' does not contain the property 'API_BASE_URL'

Encountering this error message when trying to access my API_URL as defined in the enviroment.ts file within a service class. Error: src/app/product/product.service.ts:12:25 - error TS2339: Property 'API_BASE_URL' does not exist on type '{} ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

What is the simplest method for converting a large JSON array of objects into an object containing the same data under the key "data" in TypeScript?

What is the most efficient method for converting a large JSON array of objects into an object with a key named "data" using TypeScript: Original Format: [ { "label":"testing", "id":1, "children":[ { "label":"Pream ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Unable to find module 'child_process'

Here is the content of my main.ts file: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { environment } from './environments/environment'; if ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

React.js - Issue with table not being redrawn after data filtering

I am encountering an issue with my table in Next.js where the text input is not triggering a redraw. The expected behavior is to update the table with a single search result, but currently only the top row reflects the search result. Below is my useEffect ...

developing a collection of Material UI text fields

My goal is to construct an accordion containing several textfield mui-components. I have developed a unique render function incorporating all the essential tags and syntax for creating a text field component. Now, I am looking to generate an array of text ...

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

Utilize Array.push to add 2 new rows to a table using Angular 4

I have two arrays that are almost identical, except for two items which are the fakeDates: this.prodotti.push({ idAgreement: this.idAgreement,landingStatus: this.landingStatus, landingType: this.landingType, startDate: this.startDate, expirationDate: thi ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...