typescript missing return type in array.map

Why does TypeScript allow the code below, despite it containing a type error that I would expect?

export interface Structure {
    aaa: string;
}

export function f1(): Structure[] {  // TypeScript is fine with this, but not me
    const result = [].map(certState => {
        return {
            aaa: 'aaa',
            ADDITIONAL_FIELD: 'asdf'
        }
    });

    return result;
}

export function f2(): Structure[] { // TypeScript catches the error (unlike me)
        return [
            {
                aaa: 'sdf',
                ADDITIONAL_FIELD: 'asdf'
            }
        ]
    }

Check out the link here

Appreciate your help!

Answer №1

The issue arises from the direct return of the result in function f2().

If you were to modify f2() like this:

export function f2(): Structure[] {
    const returnVal = [
        {
            aaa: 'sdf',
            ADDITIONAL_FIELD: 'asdf'
        }
    ]

    return returnVal;
}

then the compiler error would vanish.

TypeScript relies on structural typing for determining type compatibility. Therefore, in your f1() code, result is considered as

{
   aaa: string,
   ADDITIONAL_FIELD: string
}[]

which is compatible with Structure[] (no risk of type narrowing).

I'm uncertain why a direct return doesn't work, but my theory is that in f2() you are stating to the compiler that "this particular array is of type Structure[]" and it disagrees. However, when using an intermediary variable in f1(), you specify "this function returns Structure[]" and upon returning the variable, the compiler verifies that "alright, result matches Structure[]" so this function performs as described.

I would be interested to know if others can provide a more detailed explanation.

Answer №2

Recently, I discovered that Typescript strictly enforces exact types only for object literals. This means that in function f1, which does not use object literals, adding additional properties is allowed and considered valid by Typescript. However, in function f2, which uses object literals, adding extra properties is prohibited. This realization was initially concerning to me, but it simply reflects how Typescript operates.

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

Utilizing ExpressJS in a NodeJS application with ES6 and Typescript

After confirming my information, I discovered that in an ES6 application, it is necessary to import dependencies using import .. from '..' instead of var .. = require('..'). I made the necessary changes to the imports, but encountered ...

Retrieving the value of an object using a key in TypeScript

Is there a way to create an object using keys from another object and determine the type based on a string? For example: const result = rebuild(query, { name: 'string' }); // query - { name: '123', dont_need: true } // result - { n ...

Is the Codewars Snail Test a Failure, or is the Code Flawed

I have been working on a solution for the challenging codewars problem and I believe I found a cool way to solve it. However, despite testing my code in IRB and seeing it work perfectly, the last test is failing because an unexpected '1' is being ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

What is the right way to send an array using $.post method?

Below is the array I am working with: arr[0]='A'; arr[1]='B'; .... I attempted to send it using the following code: $.post('data.php',arr,function() { }); However, the desired functionality was not achieved. ...

How can I display a php array recursively within nested div elements?

I am facing a challenge with an array that has a complex data structure as shown below $array = array( 'someKey' => array( 'id' => 1, 'string' => 'some key', 'someKey2' =&g ...

What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max&ap ...

Combining arrays while deducting specific values in PHP

Let's say I have two arrays called $array1: array (size=3) 0 => array (size=5) 'id' => int 16 'project_id' => string '37' (length=2) 'description' => string 'Guitar&apos ...

Manipulating map references in C++

Apologies, just a quick question about accessing references in maps If I have: map<int,string> *items= new map<int,string>(); Can I do this? string x = &items[100]; ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

When using TypeScript in React, the event handler for the onLoad event of an image element cannot locate the properties naturalWidth and naturalHeight

https://i.sstatic.net/vPfkL.png return <img {...props} onLoad={event => { console.log(event.target.naturalWidth) }}/> I am encountering an issue trying to access naturalWidth and naturalHeight in TypeScript React. Unfortunately, TypeScript is ...

Guide on transitioning an Angular 4 project created in Visual Studio 2015 to Angular 6 with Visual Studio Code

Currently, I am collaborating on an Angular 4 project that utilizes a web API in Visual Studio 2015 update 3. This project serves as an ERP solution. My goal is to enhance the project by updating it to Angular 6, with Visual Studio Code as the primary too ...

Iterate through a multidimensional array in PHP and add a prefix to each

When the prefix value in an array is read, if the slug value is "modules", the result will be "api/v1/tenants/modules/{id}". On the other hand, if the slug value fetches, the result will be "api/v1/tenants/fetch/{id}". "slug" => "api", ...

Learn the process of merging an array element into another object and keeping track of the total count

Initially, my array contains object elements as shown below: $scope.selectedIngredient = [object1, object2, object3, object1, object2]; Next, I have a new object : $scope.selectedIngredientResults = {}; Now, I want to create a JavaScript function that ...

PHP is throwing an 'Undefined offset' error and I'm unable to determine the cause

I'm struggling to identify the cause of the "Undefined offset: 0 in" error. I have an array and I'm certain that the index is within bounds. I'm fairly new to PHP and SQL, but I need to complete this task for school. From what I can gather, ...

Learn how to utilize C# in order to read, write, and manipulate files effectively

I am looking for a solution that involves reading from a file, converting the string value to an int, iterating using a "for statement," and writing the results into another file. Each digit should be written on a new line while utilizing the WriteAllLines ...

Converting data types to bytes in the Java programming language

Just starting out in my Java journey, I stumbled upon the concept of Type Casting. Below is a snippet of code that I found: class Demo { byte b; int a=257; double d= 323.142 b=(byte)a; System.out.println(b ...

Properties cannot be accessed using the standard method in the controller; however, they function correctly when using an arrow

Currently, I am facing a challenge where traditional class methods do not allow me to access the userService. I aim to write typical class methods in my user controller like this: public async register(req: Request, res: Response, next: NextFunction): Pr ...

Exploring TypeScript: Navigating the static methods within a generic class

I am trying to work with an abstract class in TypeScript, which includes an enum and a method: export enum SingularPluralForm { SINGULAR, PLURAL }; export abstract class Dog { // ... } Now, I have created a subclass that extends the abstract cla ...

Removing a parent element in XML with C# based on the presence of a specific value in any of its child elements from an array

I am facing a challenge with an XML file where I need to check for specific numbers in child nodes and remove the parent node if any match is found against an array of excluded numbers. Here is the scenario: Array: int [] excluded = new int[] { 112659, 1 ...