Home > Mobile >  TypeScript - how to create dict type that takes different functions as a value
TypeScript - how to create dict type that takes different functions as a value

Time:12-02

export enum SomeKeys {
  FIRST_KEY = 'FIRST_KEY',
  SECOND_KEY = 'SECOND_KEY',
}

export const DICT: {
  [key in SomeKeys]: {
    title: string;
    greeter: () => {};
  };
} = {
  [SomeKeys.FIRST_KEY]: {
    title: 'first key title',
    greeter: (name: string) => ({ name }),
  },
  [SomeKeys.SECOND_KEY]: {
    title: 'second key title',
    greeter: (name: string, age: number) => ({
      name,
      age,
    }),
  },
};

Is it possible to create such a dictionary with strongly typed "greeter" function?

So I'd like to use those values as:

const { title, greeter } = DICT[SomeKeys.FIRST_KEY];
const { name } = greeter('Adam');

I hope it's clear enough to understand what's my problem

  • Related