Is there a way to iterate over an object with predetermined keys and then utilize those keys to access another object of the same type?

What I'm attempting to do next is calculate the total value of value in pounds. However, this is causing an error message stating:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MoneyType'. No index signature with a parameter of type 'string' was found on type 'MoneyType'
.

interface MoneyType {
    yuan: number,
    dollar: number,
    pound: number,
}

const CONVERSION_RATE: MoneyType = {
    yuan: 10,
    dollar: 5,
    pound: 1
}

function totalValue(value: MoneyType) {
    let totalValue = 0;
    for (let moneyType in value) {
        totalValue += CONVERSION_RATE[moneyType] * value[moneyType];
    }

    return totalValue;
}

While I know that I could use

interface MoneyType {[key: string]: number}
as an alternative, I'm curious if there's a way to maintain the specific key restrictions to yuan, dollar, and pound.

Answer №1

Approach 1 - simply convert to any type:

function calculateTotal(value: MoneyType) {
    let total = 0;
    for (let money in value) {
        total += (CONVERSION_RATE as any)[money] * (value as any)[money];
    }
    return total;
}

Approach 2 - expands the interface using a key/value format:

interface OnlyNumbers {[key: string]: number}

interface MoneyType extends OnlyNumbers {
    yuan: number,
    dollar: number,
    pound: number,
}

Additionally, consider these recommendations for your function:

  • iterate through CONVERSION_RATE members since the value passed may have additional members.
  • validate if value[money] is defined before utilizing it to prevent NaN outcomes.

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 process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

React-leaflet with TypeScript is failing to display GeoJSON Points on the map

I am attempting to display points on a map using geojson points in my react application with react-leaflet. However, for some unknown reason, the points are not rendering on the map. When I try importing a JSON file, I encounter an error: TS2322: Ty ...

Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4? This is the Chooser Component import {InputComponent} from './input/input.component' import {BlockComponent} from './block/block.component' export const FormChooser = { Block: Block ...

Accessing base class properties in Typescript: A comprehensive guide

Although I have seen similar questions on this topic, my issue is unique. I have checked my class and am using it in the same way as others who have encountered similar problems. I extended class A into class B, but for some reason I cannot access A's ...

Only implement valueChanges on the second step of the form

I am utilizing the mat-stepper with a single form. My stepper has two steps only. I am looking to make an API request for every input value change, but only when the user is on the second step. How can I accomplish this? .ts ngOnInit() { this.formGr ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

https://i.sstatic.net/tkX07.png const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this iss ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

Error message thrown when attempting to access Navigator InjectionToken in tests: ReferenceError - Navigator is not defined

I have created an abstraction for the Navigator object: export const NAVIGATOR: InjectionToken<Navigator> = new InjectionToken<Navigator>( 'An abstraction over window.navigator object', { factory: () => inject(WINDOW).navig ...

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

The Vue application is refusing to compile due to a syntax error caused by the presence of 'return' outside of a function

Upon attempting to run a build on my Vue app, I encountered the following syntax error. error in ./src/pages/Calendar.vue?vue&type=script&lang=ts& Syntax Error: 'return' outside of function. (175:4) 173 | getEventColor(event, Even ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

Implementing an interface in TypeScript and assigning it a value using generics?

I'm struggling to make sense of a type declaration I came across in the react-router library: export interface RouteComponentProps< Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.Lo ...

Explicit final argument in TypeScript

Is it feasible to define a function in TypeScript 2.7.2 and above with variable parameters, but ensuring that the final parameter has a specific type? I am attempting to craft an ambient TypeScript declaration for a JavaScript library that utilizes functi ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

Deleting a key from a type in TypeScript using subtraction type

I am looking to create a type in TypeScript called ExcludeCart<T>, which essentially removes a specified key (in this case, cart) from the given type T. For example, if we have ExcludeCart<{foo: number, bar: string, cart: number}>, it should re ...

Navigate to the parent element in the DOM

Looking to add some unique styling to just one of the many Mat dialog components in my project. It seems like modifying the parent element based on the child is trickier than expected, with attempts to access the DOM through the <mat-dialog-container> ...