Strange interaction observed when working with Record<string, unknown> compared to Record<string, any>

Recently, I came across this interesting function:

function fn(param: Record<string, unknown>) {
  //...
}

x({ hello: "world" }); // Everything runs smoothly
x(["hi"]); // Error -> Index signature for type 'string' is missing in type 'string[]'

It is logical because the Index Signature in an Array is typically a Number, whereas in a Record it is defined as a string.

However,

If I replace unknown with any, like so:

function fn(param: Record<string, any>) {
  //...
}

x({ hello: "world" }); // No issues
x(["hi"]); // Works perfectly fine now

The Question Arises: Even though only the Value has been changed to Any and not the Key type in Record, why am I not encountering any errors despite the Index Signature for arrays being Number and for records being string?

Answer №1

The reason behind this behavior dates back to historical practices. In the past, the Record<string, any> type was commonly used to define object types before the introduction of the object type. The compiler treated this type in a special way, allowing any non-null and non-undefined object types to be assigned to it. This was based on the assumption that any property within an object would be compatible with the any type (refer to #12345). To maintain backward compatibility, this behavior remains unchanged.

If you opt for Record<string, unknown> (or any other type aside from any), the source type must have a string index signature. Since arrays lack this signature, attempting to pass them as an argument will result in failure.

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

How can I remove a quadratic curved arrow tool in Fabric JS canvas after it has been created?

I'm currently working on developing a tool for creating quadratic curved arrows. For reference, I utilized a demo from the following link to build the tool: I have successfully created the tool as per my requirements. However, I am encountering some ...

The dropdown options for the input type file in Vuejs PWA are not appearing

I have created a Vue.js progressive web app that allows users to easily upload images from their mobile phones. While the app typically functions well, there is an issue where upon downloading the app to the homescreen, the image upload feature sometimes b ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

What is the best way to implement data loading on scroll in HTML with AngularJS?

I'm working with a HTML Dynamic Table <div class="clearfix reportWrapper" > <div class="reportTable"> <table class="table table-bordered footerBGColor"> <thead fix-head class="headerTable"> ...

I have chosen not to rely on Media Query for ensuring responsiveness in my Angular 2 application, and instead opted to utilize JavaScript. Do you think this approach is considered a

I am in the process of ensuring that my app is fully responsive across all screen sizes. Instead of relying on Media Query, I have chosen to use JavaScript with Angular 2 to achieve this responsiveness, utilizing features such as [style.width], *ngIf="is ...

Commit the incorrect file name with the first letter capitalized

There seems to be an issue with the git not recognizing the correct filename casing. I have a file named User.js in my workspace, but when checking the git status, it displays user.js instead. Despite repeatedly changing and committing as User.js, the gi ...

Check the box to show the corresponding sections of the form

.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

The issue of broken reactivity arises when utilizing defineStore in Pinia with options instead of storeSetup

In my current project, I've implemented two different types of Pinia storage definitions. Here's a condensed look at each: // First Storage Definition using storeSetup export const useStore = defineStore("storeId", () => { const isExpanded: ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

Output the name of the file while executing the ant process

Currently, I am utilizing YUI compressor within an ant build process to compress CSS and JavaScript files. I would like the compressor to display the name of each file it is processing as it goes along, so that in case of an error, I can easily pinpoint wh ...

VS code is showing the directory listing instead of serving the HTML file

Recently, I attempted to use nodejs to serve the Disp.html file by following a code snippet from a tutorial I found on YouTube. const http = require("http"); const fs = require("fs"); const fileContent = fs.readFileSync("Disp.html& ...

Tips for verifying that one of the two input fields is filled in Bootstrap 5 validation

I have implemented Bootstrap validation for the other input fields in this form by using the 'required' attribute. However, for these two specific fields, if at least one is not empty, then the form should be submitted. <form class="needs ...

The PHP page is not receiving the variable passed through AJAX

Within the following code snippet, there seems to be an issue with accessing the dataString variable in the comment.php page. To retrieve the variable name, I utilized $_POST['name']. $(document).ready(function(){ $("#submit").click( function() ...

Leveraging Promises in AngularJS to create a chain between two separate controllers

I've developed a provider called MyRestServices to handle my REST-Services: app.provider('MyRestServices', function() { this.baseUrl = null; this.setBaseUrl = function(_baseUrl) { this.baseUrl = _baseUrl; }; this.$get = [' ...

Tips for refreshing a webpage after returning from a redirected page

After utilizing certain logic, I am able to redirect to a new page. return RedirectToAction("Index"); If I navigate back to the previous page using the browser's back button, I would like for the "old" page to automatically update with default valu ...

Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript? JSON A: { "d": [ {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"}, {"__type":"Web.Controls.Shared.GeneralServic ...

What exactly is the functionality of this "if" statement that operates without any operators?

I've recently started learning Javascript and I'm currently going through chapter 5 of Eloquent Javascript. In my studies, I encountered a piece of code that is puzzling to me. While I understand the general method and steps of how it works, I&ap ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

When large spheres meet, Three.js/WebGL displays them as fractured

I must admit that I am not very experienced with 3D graphics. Issue In my WebGL model using Three.js, I have intentionally made two spheres collide. However, when the spheres are extremely large, they appear "broken" at the point of intersection, whereas ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...