How come Array.map permits me to input elements that do not match the generic type?

How come I am able to map properties that do not exist on type T when using Array.map<T>?

I have set strict: true in my tsconfig.json

interface MappedItem {
    foo: number;
}

const arr = [1, 2, 3];

// I would anticipate an error here, but it does not occur
arr.map<MappedItem>(n => ({ foo: n, bar: n }));

arr.map(n => {
    // Here is where the expected error occurs
    // Object literal may only specify known properties, and 'bar' does not exist in type 'MappedItem'
    const item: MappedItem = { foo: n, bar: n };

    return item;
});

Answer №1

When utilizing

arr.map<MappedItem>(n => ({ foo: n, bar: n }));

the type variable is used to indicate the return value, which in this instance is MappedItem[].

*When determining if an object fits a specific type, the compiler only verifies that the required properties (etc.) are present and match the specified types.

The objects being returned clearly fulfill the requirement set by MappedItem: they have a foo property of type

number</code. Therefore, when it behaves like a <code>MappedItem
, it is considered a MappedItem (known as duck typing).

However, if you use

const item: MappedItem = { foo: n, bar: n };

the scenario changes because *Object literals undergo excess property checking when assigned to other variables or passed as arguments, as TypeScript assumes there may be a bug in the code.

Hence, the error you encounter serves as a safety precaution.

To bypass this issue, you can employ a type assertion, such as:

const item: MappedItem = { foo: n, bar: n } as MappedItem;

You can find further details on this topic in the *handbook.

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 function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

Breaking up and Substituting text within Angular 8's HTML structure

When I retrieve data from a REST api, I need to split the name parameter at '2330' and insert a line break. For example, if the name is: ABCD 2330 This is My Name, I want the output on my screen to appear as: ABCD 2330 This is My Name // this par ...

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

What is the best way to retrieve matching values based on IDs from an imported table?

How can I retrieve values that match on ID with another imported table? My goal is to import bank details from another table using the ID and display it alongside the companyName that shares the same ID with the bank details. I've attempted several o ...

Upgrading to Angular 18 Leads to Issue with Spread Operator: 'TypeError: res is not iterable' Error

Following the migration of my Angular project from version 9 to version 18, a new error has surfaced: ERROR TypeError: res is not iterable onEscalate details.component.ts:735 RxJS 5 next _next next next error ...

How can I resolve the infinite loop issue caused by Angular Auth guard when using routing?

My current struggle lies within the authentication guard logic and routing setup. In my app-routing.module.ts file, I have defined 3 routes: const routes: Routes = [ { path: '', loadChildren: () => import('./browse/browse.mod ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

Here is the revised text: "What is the best way to send a variable to a component and retrieve it within the ng-template using

I've developed a component named "foo" that accepts a data object and displays it within an ng-template as its own variable. The issue arises when the variable inside the ng-template is of type any, lacking proper typing for checking and autocomplete ...

Using "undefined" as the discriminator in a discriminated union

My idea is to implement a discriminated union using null as the discriminator: type Result<T> = { result: T; error: null } | { result: null; error: string } If the function register() returns a Result, I could handle it like this: const { error, res ...

The 'split' property is not found in the type 'string | ArrayBuffer'. The property 'split' is not available in the type 'ArrayBuffer'.ts(2339)

"I need assistance with splitting a base64 audio file. Specifically, I want to extract only the audio data without the 'data:audio/wav;base64' text included. Can someone provide the correct code for this?" “This code snippet is intended for us ...

Module 'rxjs/internal/Observable' not found

When attempting to utilize the JwtHelperService module in my service, I encountered the following error: ERROR in node_modules/@auth0/angular-jwt/src/jwt.interceptor.d.ts(3,28): error TS2307: Cannot find module 'rxjs/internal/Observable'. In my ...

Simulating an API endpoint using a spy service (using Jasmine)

I'm currently trying to simulate an API route within a spy service using Jasmine. Being relatively new to Angular, Typescript, and Jasmine, I find myself uncertain about where to place my code - whether it should go in the beforeEach block or in its ...

Increase the vertical distance between rows in a table

Having some issues with customizing a data grid that I developed. Is there a way to eliminate the header bottom border and insert spacing between each row in the table? View Demo Example Code: <dx-data-grid style="margin-top:50px" class="table" [dat ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

Utilizing Vue 3 with TypeScript for enforcing type checking on single file components' props

In my exploration of Vuetify and other sources, I discovered that it is possible to incorporate type checking for props within the template tag. Let's consider a simple button component: <template> <div> <button>{{ label ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Which TypeScript data type is most appropriate for referencing the match object within my props?

When working with React containers/components, how can I properly reference the 'match' component from React Router DOM? interface Props { match: any // <= What data type should I use in place of 'any'? } export class ProductCont ...

Webpack and TypeScript are throwing an error stating that `$styles` is not defined

I've encountered an issue with my typescript SharePoint spfx solution. After compiling using webpack, my $styles variable becomes undefined even though I am able to use the class names directly. It seems like there might be a configuration problem at ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...