Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this:

interface Test{
   a: number;
   b: string;
   c: boolean;
}

const obj:Test = {
   a: 1,
   b: '1',
   c: true,
}

We aim to create a function that can modify the values within the object, but with type checking based on the key. While getting the value is straightforward, implementing the setter function poses a challenge:


function getValue<T , U = keyof T>(obj: T, key: U){
   return obj[key]
}

function setValue<T , U = keyof T, V???????>(obj: T, key: U, value: V>{
   obj[key] = value
}

This would enable us to achieve the following:

setValue(obj,'a',1) // no error
setValue(obj,'b',1) // results in a typecheck error

Answer №1

To simplify, you can eliminate the need for a third generic by using just T[U] since both T and U are already defined at that point.

function fetchValue<T, U extends keyof T>(obj: T, key: U){
   return obj[key]
}

function assignValue<T, U extends keyof T>(obj: T, key: U, value: T[U]){
   obj[key] = value
}

assignValue(obj,'name', 'John') // no error
assignValue(obj,'age', 30) // typecheck error

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

Exploring the benefits of leveraging TypeScript with AWS NodeJS for improved stacktrace visibility over traditional JavaScript

I'm contemplating the idea of transitioning my existing JavaScript codebase to incorporate TypeScript in NodeJS. One aspect that I am concerned about is being able to view the stack trace in AWS CloudWatch (request log) in case an error occurs during ...

Navigating any object array in TypeScript and retrieving its properties

Consider the following JSON data object: var dataObjects = [ { "Name": "Date & Time", "Type": "Date", "Value": "2019-12-11" }, { "Name": "Activity", "Type": "String", ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

What is the best way to dynamically insert content into a PDF using pdfmake?

In my quest to dynamically generate PDFs using pdfmake, I've encountered an issue with creating dynamic rows based on data. To illustrate, here is a simplified version of the code: getDocumentDefinition(img: string, data: DataResponse, user: UserResp ...

Angular Material Select Dropdown that emits the entire object item, rather than just the value

When using the Angular Material select dropdown API, only a value is emitted. Both [(ngModel)] and (selectionChange) will only emit a single member, not the entire object's data fields. For example, it will only emit something like food.value = 2, wi ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Generate a pre-signed URL for an AWS S3 bucket object using Typescript in NextJS, allowing for easy file downloads on the client-side using @aws-sdk/S3Client

In the utilization of v3 of the S3Client, it appears that all existing examples are based on the old aws-sdk package. The goal is for the client (browser) to access a file from S3 without revealing the key from the backend. From my research, it seems tha ...

Is it possible to record the attributes within an interface in TypeScript?

Imagine I have the following scenario: interface Validator { validate: (value: string) => boolean; errorMessage: string; } interface EditDialogField { label: string; prop: string; required?: boolean; type: 'input'; validators?: ...

Creating a custom type for the parameter of an arrow function in Typescript

I need assistance defining the type for an object parameter in an arrow function in TypeScript. I am new to TypeScript and have not been able to find any examples illustrating this scenario. Here is my code: const audioElem = Array.from(videoElem.pare ...

Optimal strategies for managing server-side validation/errors in Angular applications

Back in the day, I used to retrieve HTTP responses with a TypeScript object. validateTokenHttp(token: string): Observable<User> { return this.http.get<User>(`${environment.api}/auth/verifyToken/${token}`); } Sometimes it would return a Us ...

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

Describe the TypeScript type for an object with constant keys

My query resembles the one found in this Typescript interface definition question, but has a slight variation. I am beginning with an object where the keys are constants: const KEYS = { KEY1: 'hello', KEY2: 'world' } as const; How ...

Creating a new element in the DOM when a button is clicked using Angular 2+

Greetings! I am currently in the process of learning how to manipulate the DOM using Angular 2+ and my goal is to incorporate an Input field with type email when the click event is activated. Despite conducting some research via Google, I have been unable ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

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 ...

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...