Using TypeScript to define parameter types to update an object's key and value

I need assistance in creating a function that can update an object's value based on the provided key and new value while ensuring type safety.

type GroceryStore = {
    isOpen: boolean;
    offers: string[];
    name: string;
};

const myGroceryStore: GroceryStore = {
    isOpen: true,
    offers: ["banana", "apple", "kiwi"],
    name: "FruitMart",
};

// How can we ensure type safety?
const updateGroceryStore = (key: keyof GroceryStore, value: any) => {
    myGroceryStore[key] = value;
};

// Should execute correctly
updateGroceryStore("isOpen", true);

// Should trigger TypeScript error
updateGroceryStore("isOpen", "Walmart");

// Should trigger TypeScript error
updateGroceryStore("isOpen", ["orange", "pear", "pineapple"]);

Answer №1

To effectively capture the key passed in, you can utilize a type parameter and then employ a type query to specify the type of value in relation to the specified parameter:

const updateSupermarket = <K extends keyof SuperMarket>(key: K, value: SuperMarket[K]) => {
    mySuperMarket[key] = value;
};

Playground Link

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

Broaden the scope of the generic interface utilized within the package

Wanting to incorporate automatic behaviors in RTK Query, I decided to implement debounced mutations and handle optimistic updates before the actual mutation request is made. The implementation has been successful so far. However, I am now focusing on gett ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

The quantity of elements remains constant in the EventEmitter

The Grid component is structured as follows: export class GridComponent { @Output('modelChanged') modelChangedEmitter = new EventEmitter(); private valueChanged(newValue: any, item: Object, prop: string) { item[prop] = newValue; ...

The metadata for Company#companyTypesLinks could not be located. Please verify that the entity object has been correctly specified

I am facing an issue with the relationship between my entities. I have tried everything, but I still encounter the same problem. Here are my scripts: Company.entity.ts export class Company extends AppBaseEntity { @Column('text', { name: ' ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Utilizing TS2722 alongside restrictive parameters in tsconfig

I have encountered these errors due to the presence of the strictNullChecks parameter, which is activated by the strict configuration in the tsconfig.json file. It appears that when arguments.length === 2, the ab function should be available (thanks to Fun ...

Excessive recursive template causing call stack overflow in tree

By utilizing this particular gist, I am able to effortlessly showcase a tree structure. https://i.sstatic.net/yUNyw.png The aspect I aim to alter is how the first level is presented, as illustrated below: https://i.sstatic.net/Wg7JG.png Despite attempt ...

typescript challenging syntax within mix-ins

type Constructor<T> = new (...args: any[]) => T; function f1<T extends {}>(naked: Constructor<T>): any { return class dressed extends naked { } // error } function f2<T extends Constructor<{}>>(naked: T): any { re ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Type with self-reference in index

Looking to create an interface with a mix of known and unknown members that should all have the same type. Here's what I have in mind: interface Foo { name?: string; [others: string]: Foo; } This setup would allow me to create something like ...

What is the best way to design a versatile instanceof function that returns the object if it matches the specified type?

I am currently working on developing a function with this structure: function isInstance<T>(s: T): T | boolean { return (s instanceof T) && s; } The purpose of this function is to return the value as that type if it is an instance, otherwise it re ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

Error: React-Redux Provider is being called incorrectly

I am currently working on a small application to get familiar with using Redux Toolkit. My understanding of React/Redux mainly comes from an outdated Udacity course. Although the error message lists the top 3 reasons for this particular error, none of the ...

Tips for utilizing generic object utilities for objects defined by interfaces in Typescript

I am facing an issue with my code where I have defined an object with an interface and a utility function to clean up the object by removing undefined properties. However, when I try to pass this object to the utility function, Typescript throws an error. ...

What method could I use to verify that my Angular 2+ login function has been invoked successfully?

Can anyone provide guidance on how to effectively verify if a function has been executed within the interaction of a component and a service? I welcome any insights or suggestions that can help me address this challenge! ...

Can I combine tuple types in Typescript?

type A1 = ['x','y','z'] type A2 = ['u','v','w'] type AN = [.., .., ..] type C = Combine<A1,A2,...,AN> //or Combine<[A1,A2,...,AN]> //resulting in ['x','y','z& ...

Angular 6: A class with no 'default' modifier must explicitly specify a name

I am encountering this error in my ts.file, as I delve into the world of Angular/Ionic. Can anyone help identify the possible reasons for this? I have attempted multiple solutions to address it, but unfortunately, none have proven successful. import { Co ...