Please indicate the type of object to be used with lodash's reduce

When using Lodash's _.reduce() with an object, I encountered a TypeScript error (as shown below) that indicates it expects an array instead. How can I resolve the type mismatch in this scenario?

interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;

// Argument of type 'Fees' is not assignable to parameter of type 'NumericDictionary'.
// Index signature is missing in type 'Fees'.
total += _.reduce(fees, (sum: number, v: number) => sum + v, 0);

Answer №1

Unfortunately, specifying the type of fees as Fees changes it from being treated as an Object, which would have passed the check for NumericDictionary<T> due to TypeScript's structural typing.

Here are two possible solutions:

1) Remove the type declaration from the fees variable. TypeScript can infer the type and when you pass the object where a Fees instance is required, it will work because of structural typing.

interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;
total += _.reduce(fees, (sum, v) => sum + v, 0);

2) Define Fees as an extension to NumericDictionary<number>

interface Fees extends _.NumericDictionary<number> {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;    
total += _.reduce(fees, (sum, v) => sum + v, 0);

Also, there's no need to declare the types of sum and v in the reduce function as they will be inferred from the type of fees.

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

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

Angular 6 is throwing an ERROR TypeError because it is unable to access the property 'length' of a null object

Recently delving into Angular 6, I've encountered an issue with two components: app.component.ts and products.component.ts, as well as a service file. In the products component, I am receiving a JSON response in the ngOnChanges method. My goal is to ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Angular Injection Error: Received 1 argument instead of the expected 0

Although I have already looked for a solution to this problemhere, I am still struggling to resolve the error on my own. I recently started an Ionic project and followed this link to implement authentication using Angular. Everything seemed to be working ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Can you dynamically create screens within the React Navigation Tab Navigator using code?

My goal is to dynamically generate tabs in React-Navigation based on the values retrieved from an array, and pass the data from each array value to the corresponding screen. For instance, if there are 2 accounts, I expect 2 tabs with unique screens for eac ...

What makes TS unsafe when using unary arithmetic operations, while remaining safe in binary operations?

When it comes to arithmetic, there is a certain truth that holds: if 'a' is any positive real number, then: -a = a*(-1) The Typescript compiler appears to have trouble reproducing arithmetic rules in a type-safe manner. For example: (I) Workin ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

What is the method for converting a string[] array to a record<string, boolean> format in typescript?

I have a string array that contains values I want to keep and use to create a new array called Record. For each value in the userValue array. For example: userValue: string[] = ["1111","2222","3333","4444"]; selectedOptions: Record<string, boole ...

Redux ConnectedProps will always have a type of never

I am facing an issue while attempting to connect a component to my Redux store following the steps outlined in the official documentation guide. The props that are connected seem to be coming through as type never. Here is a snippet of my code: Type defi ...

What is the alternative to the deprecated 'combineLatest' method in rxJs and how can it be replaced?

Recently, I came across a situation where I had implemented a method using the combinlatest rsjx/operator. It was working perfectly fine. However, Sonar flagged it as deprecated and now I need to update it to the latest version. When I tried to simply re ...

Attempting to perform an API invocation on a distant endpoint utilizing NestJS

var unirest = require("unirest"); var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data"); req.query({ "ingr": "1 large apple" }); req.headers({ &qu ...

Differences between Arrays of Numbers and Objects in Typegoose

Exploring Typegoose and encountering a puzzling issue. I defined a class with a field meant to store an array of numbers like this: class A { ... some other properties ... @prop({ required: true }) public nums!: number[]; } Here's a snippet of ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

The VSCode Extension fails to launch after being packaged

I'm currently working on a straightforward VSCode extension that scans the active open file for any comments containing "//TODO: " and then presents a list of all TODO comments in a webview sidebar tab. While I have a functional prototype that runs s ...

I have to create a duplicate for the clipboard containing a dynamic variable in Angular

CSS Note: The Technical.url variable in the specification is constantly changing, and every time I click the button, I want to copy the URL. <div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="" ...

The inferred type of a TypeScript promise resolved incorrectly by using the output value from a callback function

Although some sections of the code pertain to AmCharts, the primary focus of the question is related to TypeScript itself. The JavaScript functions within the AmCharts library perform the following tasks: export function createDeferred(callback, scope) { ...

Recent TypeScript update causing async server component to encounter errors

I'm in the process of learning how to develop a web application using next.js and typescript. On my homepage, I want to retrieve some data and then display it. I am fetching my data using an asynchronous function, but when I label my component as asy ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...