What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

  type ExpectedType = Array<{ name: number, gender?: string }>

  function go1(p: ExpectedType) {

  }  

  function f() {
    const a = [{name: 1, age: 2}]
    go1(a)                   // no error shown
    go1([{name: 1, age: 2}]) // error displayed 'Object literal may only specify known...'
    go1(['no matter'].map(n => ({name: 1, age: 2}))) // no issue arises 
  }

The TypeScript code outlined above brings up an interesting inquiry - why do the last three lines appear to be identical? How come the first line is accepted without issues, while the second line raises an error and the third line does not?

To see it in action on the TypeScript playground, visit: playground

Answer №1

When you assign variable a to the parameter of go1(), it may seem like you are just assigning one variable to another. However, if the type of a is compatible with the parameter variable type, everything works fine. But if you were to change the type to { name: number, gender: string }, you would encounter a type error.

If you were to assign a literal object as the parameter instead, there would be no issues since there is no need for type casting, allowing the compiler to catch any potential type errors.

For more information, you can refer to this resource.

The basic rule of TypeScript’s structural type system states that x is considered compatible with y if y has at least the same members as x. For example:

interface Named {
    name: string;
}

let x: Named;
// The inferred type of y is { name: string; location: string; }
let y = { name: "Alice", location: "Seattle" };
x = y;

When determining whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y. In the given case, y must have a member named name that is of type string, which it does, thus allowing the assignment.

Answer №2

After conducting thorough research, I have discovered that the answer can be found in TypeScript's official documentation.

The distinguishing factor among the last three lines lies in the nature of the parameter being passed. In the second line, the parameter is an object taken literally, whereas in the other two lines it is not. TypeScript handles literal parameters and non-literal parameters differently:

Excess Property Checks

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

What is the method for extracting user input from a text box on a webpage?

Having trouble with retrieving the value from a text box in my search function. SearchBar Component import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.compon ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

Error property for text field validation in Material UI allows for easy checking and validation of

In my React UI app, I am implementing an error property to highlight a text box in red when it exceeds the maximum character limit. The logic for this is based on https://mui.com/components/text-fields/#validation Currently, the red color only appears whe ...

Initiate a file download following the redirection of a user to a new page in NodeJS/Express

Overview I am currently developing a NodeJS project using Express. In the application, there are buttons visible to the public that trigger file downloads. These buttons are linked to protected routes which will redirect users to a login page if they are ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

What is the best way to style the current element being targeted in React?

In my React application, I am trying to dynamically adjust the height of a textarea element based on its content. I want to achieve this by utilizing an 'onchange' listener to trigger a resize function. While I have successfully implemented the ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Tips for choosing an <li> element with JavaScript

<style> .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; dis ...

React-query v5 - Updating or fetching outdated query

I am currently using the Tanstack/react-query v5.12.2 library and I am facing an issue with invalidating or refetching an inactive query using the useQueryClient() function. It seems that something has changed in version 5 of the library. I have tried sett ...

What could be causing the HTML5 canvas not to show up on the screen?

<!doctype html> <html> <head> <title>Canvas test</title> </head> <body> <script type="text/javascript"> c = getElementById('canvas'); ctx = c.getContext("2d")' ctx.fillRect(10,10,10,10); </s ...

The connections of directives

In my Angular application, I am encountering an issue while trying to enhance the functionality of a third-party directive with my own custom directive. The problem lies in the order of instantiation of these directives. The intended usage of the directiv ...

Maximum Age Setting for Iron Session Cookie

Currently, I am attempting to configure a Next JS application with iron-session and a 'remember me' feature. The objective is for the maxAge of the iron-session cookie to be extended to a week if the user selects the remember me option on the log ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...

Issue encountered while attempting to remove a row from a table (JavaScript)

I'm encountering an error when attempting to delete a table row: "Uncaught ReferenceError: remTable is not defined index.html:1:1". When I inspect index.html to identify the issue, I find this: remTable(this) This is my code: const transact ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

The asyncData function in Nuxt is throwing a surprise setTimeout (nuxt/no-timing-in-fetch-data)

Having trouble running a code on my pages/posts/index.vue page where I keep getting an error message 'Unexpected setTimeout in asyncData'. Can anyone provide assistance in understanding this error and suggest if any additional plugins are needed? ...