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

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Tips for creating an effective unit test using Jest for this specific controller

I'm currently grappling with the task of unit testing my Controller in an express app, but I seem to be stuck. Here are the code files I've been working with: // CreateUserController.ts import { Request, Response } from "express"; impor ...

You cannot call this expression. The data type 'Boolean' does not have any callable signatures

As I delve into learning a new set of technologies, encountering new errors is inevitable. However, there is one particular type of error that keeps cropping up, making me question if I am approaching things correctly. For instance, I consistently face t ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

Preventing going back to a previous step or disabling a step within the CDK Stepper functionality

In my Angular application, there is a CdkStepper with 4 steps that functions as expected. Each step must be completed in order, but users can always go back to the previous step if needed. For more information on CdkStepper: https://material.angular.io/cd ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Uncovering the Full Scope of a LinkedIn Profile with Typescript

Hello, I am currently in the process of developing an Ionic2 framework app that includes social login functionality. Up to this point, I have successfully integrated Google Plus and Facebook buttons. Now, I would like to add LinkedIn login as well. The c ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

What is the correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Leveraging Firestore Errors within Cloud Functions

Is it possible to utilize the FirestoreError class within Firebase cloud functions? The goal is to raise errors with a FirestoreError type when a document or field is not found in Firestore: throw new FirestoreError(); Upon importing FirestoreError using ...

Issue arose following the update from Angular 5 to 6, impacting the VSTS build process

Upon upgrading from Angular 5 to 6, I successfully got it running locally. It builds and compiles with --prod. Integration into an .NET MVC application went smoothly. However, when the build on VSTS is triggered, a series of errors surface: node_modules&b ...

TypeScript failing to recognize dependency for LitElement

Currently, I am encountering an issue with importing two lit elements in my project, namely RootElement and CustomElement. The problem arises when trying to import CustomElement, which unlike RootElement does not show up properly on the UI. My attempt to i ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

Implementing Angular 2 - Steps to ensure a service is accessible within the app module

I'm running into an issue trying to utilize a function within a service that I believed was globally accessible. The service in question is named SavedNotificationService: import { Injectable } from '@angular/core'; @Injectable() export cl ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

What is the best way for a function to accommodate various types that adhere to an interface?

How can we create a function that can accept multiple types with a common interface? Let's consider the example: interface A {a: number} type B = {b: string;} & A type C = {c: string;} & A function acceptA(a: A) { return a } acceptA({a ...