typescript - get type by indexing object interface with variable

625 Views Asked by At

Hi I would like to index object interface with a variable

so heres my interfaces:

interface OptionsRedux {
  default_route: DefaultRoute[];
  insurance_company: InsuranceCompany[];
  marital_status: MaritalStatus[];
  reason: Reason[];
  termination_reason: TerminationReason[];
}
type optionGroupTypes = keyof OptionsRedux;

Right now my code looks like this:

interface GetOptions {
  type: ActionTypes.getOptions,
  payload: {group: optionGroupTypes, values: OptionsRedux[optionGroupTypes]}
}
export const getOptions = (
  group: optionGroupTypes,
  values: OptionsRedux[optionGroupTypes]
): GetOptions => ({
  type: ActionTypes.getOptions,
  payload: { group, values },
});

which gives me type for payload value:

DefaultRoute[] | InsuranceCompany[] | MaritalStatus[] | Reason[] | TerminationReason[]

but I would like to do something like this:

interface GetOptions {
  type: ActionTypes.getOptions,
  payload: {group: optionGroupTypes, values: OptionsRedux[group]}
}

this gives me that the group is undefined.

my objective is, that when I would use function getOption("default_route", values), the values would have to be:

DefaultRoute[]

Any ideas? cant find anything that would work

2

There are 2 best solutions below

0
Mohammed Aamier On

This is the right way to create a partial interface

interface IPerson {
firstname: string,
lastname: string,
[key: string]: any
}

Create an object of type IPerson

const person: IPerson {
firstname: 'John',
lastname: 'Doe',
phonenummber: 82184
}

I hope this will help you

0
Arin Taylor On

You can achieve this with generics. To expand on your examples:

interface GetOptions<T extends optionGroupTypes> {
  type: ActionTypes.getOptions,
  payload: { group: T, values: OptionsRedux[T] }
}

export const getOptions = <T extends optionGroupTypes>(
  group: T,
  values: OptionsRedux[T]
): GetOptions<T> => ({
  type: ActionTypes.getOptions,
  payload: { group, values },
});

By adding the generic type T, the group and values types are kept in sync with each other. T is the specific chosen type, rather than the union of all the types.