Setting a restriction on the maximum number of keys allowed to be passed through generics and indexed access types in Typescript for a specific function

Apologies for the title confusion, let me clarify my problem.

I am utilizing a React state management library where my application state is structured as follows:

type ApplicationState = {
  loading: boolean;
  data: string[];
  colors: number[];
  alerts: any;
  error: string;
}

const state: ApplicationState = {
  loading: false,
  data: [],
  colors: [],
  alerts: {},
  error: "some error"
}

I have a setter function in place to ensure that the key corresponds to a valid key in ApplicationState, and that the value matches one of the corresponding types in the state.

const mySetter: <K extends keyof ApplicationState>(key: K, value: ApplicationState[K]) => ApplicationState = (key, value) => {
  return {
    ...state,
    [key]: value,
  }
}

My query pertains to how I can restrict the key (K) to only certain specified types within the state (such as limiting it to changing loading, alerts, and error)? Currently, the setup allows usage of any key (K) from ApplicationState.

Thank you for your assistance!

Answer №1

To define a union type, you can simply use 'loading' | 'error' as shown below:

type AppStatus = {
  loading: boolean;
  data: string[];
  colors: number[];
  alerts: any;
  error: string;
}

const status: AppStatus = {
  loading: false,
  data: [],
  colors: [],
  alerts: {},
  error: "an error occurred"
}

type PossibleAppStatuses = 'loading' | 'error';

const updateStatus: <K extends PossibleAppStatuses>(key: K, value: AppStatus[K]) => AppStatus = (key, value) => {
  return {
    ...status,
    [key]: value,
  }
}

You could also specify the type argument as

<K extends ('loading' | '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

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Error: The use of await in RequestPromise is not valid

I encountered a TSLint error stating "Invalid 'await' of a non-Promise value." in the line of code below: const response: RequestResponse = <RequestResponse>await this.apiRequest(uri); Additional code context: private apiRequest: Request ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

Ways to update the UI dynamically in Angular without the need to refresh the entire page

On my page, I have multiple charts and I'm facing an issue where the chart UI does not update immediately when I try to make a delete call by clicking the delete button. I always have to refresh the browser to see the changes. I have provided the ful ...

How can users create on-click buttons to activate zoom in and zoom out features in a Plotly chart?

I am currently working on an Angular application where I need to implement zoom in and zoom out functionality for a Plotly chart. While the default hoverable mode bar provides this feature, it is not suitable for our specific use case. We require user-cr ...

I am looking to update my table once I have closed the modal in Angular

I am facing an issue with refreshing the table in my component using the following function: this._empresaService.getAllEnterprisePaginated(1);. This function is located in my service, specifically in the modal service of the enterprise component. CODE fo ...

Issues with Typescript and TypeORM

QueryFailedError: SQLITE_ERROR: near "Jan": syntax error. I am completely baffled by this error message. I have followed the same steps as before, but now it seems to be suggesting that things are moving too slowly or there is some other issue at play. ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

Issue with exclude not functioning in tsconfig.json for Angular Typescript deployment

I am encountering an issue with a module within the node_modules directory while compiling my Angular 4 project. The error messages I'm receiving are as follows, even after attempting to exclude the problematic module in the tsconfig.json file. Can an ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

Tips for verifying the presence of a specific value within an array of union types

Given an array of a specific union type, I am trying to determine if a string from a larger set that includes the union type is present in the array during runtime: const validOptions: ("foo" | "bar")[] = ["foo", "bar"] type IArrType = typeof validOptions ...

Eliminating tail recursion for conditional types is ineffective

In TypeScript version 4.5, the feature of tail call optimization was introduced for recursive generics. The code snippet below calculates Fibonacci numbers (in unary) up to F12, but encounters an error when trying to compute F13 due to the "Type instantiat ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

The latest version of Reinforced.Typings, 1.4.0, is causing build crashes when upgrading from the previous version 1

Recently, I updated my C# 4.5.1 .NET library named "ViewModels" to the newest 1.4.0 version of the Reinforced.Typings library/tool using NuGet. This tool allows me to convert my C# code to .ts files. During the upgrade process, I chose not to overwrite th ...

Removing Angular Template space highlights in WebStorm can be done easily with a few simple steps

Is there a way to remove space highlights in Angular / TypeScript using WebStorm 2019? https://i.stack.imgur.com/vfudR.jpg Many thanks, Sean ...

Having trouble accessing undefined properties? Facing issues with the latest Angular version?

Why am I encountering an error and what steps can be taken to resolve it? Currently using the latest version of Angular. ERROR TypeError: Cannot read properties of undefined (reading 'id') Here is the JSON data: { "settings": [ { ...

Toggle Button in Angular upon Form Changes

I am currently working on a bug that involves preventing users from saving data if they have not entered any information in the form. The form structure is as follows: private buildAddressPopupForm() { this.form = this.fb.group({ roles: [''], ...

What is the process of retrieving a string in a method within an Ionic TypeScript file and storing it in a variable?

Having trouble returning a string to another method in an Ionic TypeScript file. Our goal is to return JSON.stringify(res) and assign it to the stringset variable. We initially tried testing by simply returning the string "hi", but even that did not work. ...

Angular 5 Dilemma: Exporting UI Components without Locating Template

My current project involves developing UI Components that will be used in various web projects within the company. Our plan is to publish these UI components as an npm package on our local repository, and so far, the publishing process has been successful. ...