How is it possible that there is no type error when utilizing copy with spread syntax?

When I use the map function to make a copy of an array of objects, why doesn't it throw an error when adding a new property "xxx"? This new property "xxx" is not declared in the interface.

interface A{
  a:number;
  b:string;
};

let originalArray:A[] = [{a:1, b:"a"}, {a:2, b:"b"}];

let copiedArray:A[] = originalArray.map((item)=>({...item, xxx:"abc"}));

Answer №1

Since the variable b can still be assigned to variable a.

Let's look at the following example:

interface A {
  a: number;
  b: string;
};

interface B {
  a: number;
  b: string;
  xxx: string;
}

declare var a: A[]
declare var b: B[]

a = b // ok
b = a // error

b has all the properties of a, making it safe to assign b to a.

However, it is not safe to assign a to b.

interface A {
  a: number;
  b: string;
};

interface B {
  a: number;
  b: string;
  xxx: string;
}


let a:B[] = [{a:1, b:"a"}, {a:2, b:"b"}]; // error

This is because they are covariant.

If you are interested in contravariance, check out this example:

interface A {
  a: number;
  b: string;
};

interface B {
  a: number;
  b: string;
  xxx: string;
}

class C<T>{
  method = (a: T) => { }
}

let a: C<A> = new C()
let b: C<B> = new C()

// vice versa
a = b // error
b = a // ok

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

Incorporate an external library

I am currently facing a challenge in my angular2 project where I need to import a 3rd party library. Here are the steps I have taken so far: ng new myproject npm install --save createjs-easeljs npm install @types/easeljs However, I am stuck at this poin ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Stop the transmission of ts files

Recently, I noticed that when using node JS with Angular-CLI, my .ts files are being transmitted to the client through HTTP. For example, accessing http://localhost/main.ts would deliver my main.ts file to the user. My understanding is that ts files are s ...

Error occurs in the compiler when a variable is utilized as a function

I'm currently facing an issue while compiling Typescript where the compiler is throwing an error: TypeError: myVariable is not a function at Object.<anonymous> (/home/anon/Desktop/Typescript/main.js:37:1) at Module._compile (internal/mo ...

Error in Node.js with MongoDB: Array of OptionalId<Document> Typescript typings

I have successfully established a connection and written to my MongoDB collection, but I am encountering a type error that is causing some confusion. Below is the code snippet along with the error message: interface Movie { id: number; title: string; ...

Angular does not display HTML content until the requested http data has been fully loaded

I am experiencing an issue where certain HTML content does not load until the component has received data from an API call through a service. Below is the relevant code snippet: import { ApiService } from './services/api.service'; @Component({ ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

Error: Unable to call function onPopState from _platformLocation due to TypeError

After building an angular application, I encountered a strange issue where it runs smoothly in non-production mode but throws an error when running with --prod: Uncaught TypeError: this._platformLocation.onPopState is not a function I have double-checked ...

There is a potential for the object to be 'undefined' when calling the getItem method on the window's local storage

if (window?.sessionStorage?.getItem('accessToken')?.length > 0) { this.navigateToApplication(); } Encountering the following error: Object is possibly 'undefined'.ts(2532) Any suggestions on how to resolve this issue? I am attem ...

Guide on how to conditionally display a button or link in a Next.js Component using TypeScript

Encountering a frustrating issue with multiple typescript errors while attempting to conditionally render the Next.js Link component or a button element. If the href prop is passed, the intention is to render the Next.js built-in Link component; otherwise, ...

Why does the data appear differently in Angular 9 compared to before?

In this particular scenario, the initial expression {{ bar }} remains static, whereas the subsequent expression {{ "" + bar }} undergoes updates: For example: two 1588950994873 The question arises: why does this differentiation exist? import { Com ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

Dramatist - shutting down an angular pop-up dialog

I am currently utilizing the Playwright tool to carry out testing on an angular application. One particular scenario involves a modal that is displayed by default when a page is loaded. Despite my best efforts, I have been unable to successfully close this ...

Solve TypeScript React error TS(2339) by resolving issues with extending a React.FC and using static property of type JSX.Element for uninitialized components

Currently, in VSCode, the typescript compiler is at TypeScript React 4.4.2 and it's pointing to a TS(2339) error: Property 'Col' does not exist on type 'FC<GridProps>'. I have attempted to add this prop to GridProps: export ...

Exploring the capabilities of google-diff-match-patch within the Angular framework

Seeking a way to incorporate the google diff/match/patch lib into an Angular application for displaying the variance between two texts. Here's how I plan on using it: public ContentHtml: SafeHtml; compare(text1: string, text2: string):void { var ...

The issue with the react-diagram stemmed from a conflict with @emotion/core

During the installation of react-diagrams by projectStorm, I encountered some errors which are shown in the following image: errorImg Despite attempting to downgrade the version of '@emotion/core' to ^10.0.0, the issue persisted. Here is a view ...

Struggling to figure out webhooks with Stripe

I have encountered a strange issue while using Stripe webhooks to process payments on my website. When I set the currency to USD, it prompts me to provide an address outside of India, which is expected. However, when I change the currency to INR, the addre ...

Utilizing IonPage and DeepLinkMetadataType in Ionic 3 for tab navigation: Eliminating the need for tab-0

One of the pages on my site contains tabs that are only loaded when clicked: explore.html <ion-tabs> <ion-tab [root]="tab1Root" [tabTitle]="hotTitle" tabIcon="flame"></ion-tab> <ion-tab [root]="tab2Root" [tabTitle]="searchTitle ...

React: Dealing with unsuccessful imports

Whenever a device loses internet connection, my app crashes due to an imported component that relies on Google Maps. To address this issue and prevent the app from showing a blank screen, I want to intercept the failed Google Maps import and display an err ...