Home > Mobile >  Typescript: Limit the number of keys that can be passed via generics and indexed access types for a
Typescript: Limit the number of keys that can be passed via generics and indexed access types for a

Time:04-08

Sorry about the title, maybe it's a little confusing? Let me explain my issue.

I'm using a React state management library where I have an application state that looks like the following:

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

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

Then I have a setter, which makes sure that the key is a key of ApplicationState, and that the value is one of the value types of Application state.

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

So my question is, how do I constrain the key (K) to be only of certain types of the state (for example, I only want it to change loading, alerts and error)? The way it's currently set up, it allows for any key (K) of ApplicationState to be used.

Thanks for your help!

CodePudding user response:

Just use a union type like 'loading' | 'error', for example:

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

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

type SomeApplicationStates = 'loading' | 'error';

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

You may also write <K extends ('loading' | 'error')> for the type argument.

  • Related