Is there a way to limit the keys of T to only number fields, where T[keyof T] is a number

I'm looking to restrict the field parameter within this function:

function calculate<T>(source: T[], field: keyof T) {
   for(const item of source) {

   }
}

The goal is to ensure that item[field] will always be a number.

Is there a way to achieve this?

UPDATE:

In addition, how can I limit the non-generic function parameter like so:

function bar(field: keyof MyObject){ }

to prevent situations like

interface MyObject { name: string, value: number; }
bar("name"); // should result in a compiler error

Answer №1

If you want to restrict the property value of field to only numbers, you can utilize a Record type as shown below:

function calculateSum<T extends Record<K, number>, K extends string>(items: T[], field: K) {
   let sum = 0;
   for(const item of items) {
       const val = item[field]; 
       sum += val;
   }
   return sum;
}

Test it out:

calculateSum([{foo: "adsf", numField: 3}, {numField: 10}], "numField") // Result should be 13
calculateSum([{numField: 3}, {numField: "duuhh"}], "numField") // This will throw an error

Interactive Playground

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's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

I am interested in transforming an Angular 2 observable into a custom class

Having recently delved into the world of angular2, I've spent countless hours trying to tackle a particular challenge without success. My goal is to convert an observable from an HTTP call and store it in a class. Below are the key components involve ...

What could be causing the index.tsx file to not locate the Clock Module?

Here is the code snippet I have in my index.tsx file. import Clock from "./utility/clock"; And this is my tsconfig setup. { "compilerOptions": { "sourceMap": true, "noImplicitAny": true, "module": "es6", "target": "es5", ...

Develop a user interface designed specifically for a subset of JSX.Elements or ReactElement

For better organization, I decided to create an interface called IconInterface to group all my icons: import { IconProps, CaretProps, CheckboxProps } from "./IconProps"; interface IconInterface { (props: IconProps | CaretProps | CheckboxProp ...

Different categories of properties within a generic function

I'm attempting to modify certain fields of my object using field names. Here is the code snippet I have written: interface Foo { a: number[], b: string[], } type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] } function test<T ex ...

Restrict the properties of an object to match the properties of a different object

I am currently developing an Object patching utility function with the following code snippet class Test{ a:number; b:number; } var c:Test={a:0,b:1} function patchable<T>(obj:T){ return { patch:function<K>(prop:K){ return patc ...

Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component? I have a method in the piechart component that I want to access from the app component using ViewChild. In my piechart.component.ts file: export class PiechartComponent { constructor() ...

Why won't T.chain chain properly in Effect-ts?

I have a simple program that I've been working on: import * as T from "@effect-ts/core/Effect"; import { pipe } from "@effect-ts/core/Function"; import { tag } from "@effect-ts/core/Has"; interface ConsoleModule { log: ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

TypeScript focuses on checking the type of variables rather than their instance

Is there a way to pass a type (not an instance) as a parameter, with the condition that the type must be an extension of a specific base type? For example abstract class Shape { } class Circle extends Shape { } class Rectangle extends Shape { } class ...

Using MatTableDataSource in a different Angular component

I am working with two components, namely Order and OrderDetail. Within the Order component, I have a MatTableDataSource that gets populated from a service. OrderComponent Prior to the constructor listData: MatTableDataSource<DocumentDetailModel>; ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...

Why isn't my Next.js middleware working properly with TypeScript?

My issue arises from the fact that, despite following the documentation, the middleware in Next.js is not functioning as I anticipated. I experimented with what I thought was the simplest middleware possible. I expected that when navigating to /, a conso ...

Why does the final value appear when passing an incrementing counter as a prop to multiple React Components created in a loop?

I am currently unraveling the concept of closures in JavaScript. Within this code snippet, I am cycling through the values of the 'items' array using a foreach loop. I have defined a let variable named "count" outside the scope of the loop. Afte ...

Assign a unique identifier to the Angular mat-checkbox component

I need to attach an ID to an Angular material checkbox. I have an object called item. When I check the HTML code, it shows 'item.id + '-input'. However, when I bind the name, it works fine with just 'item.id'. Below is my current ...

The element is absent in Type {}, however, it is mandatory in Type '&' and '&' cannot be designated to String Index Type Errors

I have a goal of passing the logged-in user's email address to a 'dict' as a key, fetching its corresponding token value, and using it as a query parameter for an API call. The user's email is retrieved from the user data upon login, sp ...

Bringing in TypeScript declarations for the compiled JavaScript librarybundle

I have a custom library written in TypeScript with multiple files and an index.ts file that handles all the exports. To consolidate the library, I used webpack to compile it into a single index.js file but now I'm facing challenges importing it with ...

jester: constantly jest navigator's mock & check against userAgent/vendor

Purpose: Need to iterate through different combinations of the userAgent Simulate navigator behavior Execute the test Observation: I simulated the navigator.userAgent, simulation works as planned, first test executes as expected Second simulation is per ...