A
A
Alexey Nikolaev2019-11-02 17:22:49
typescript
Alexey Nikolaev, 2019-11-02 17:22:49

How to make an object's dynamic key based on the values ​​of another object?

Good day.
There is an object that is a map of aliases and possible values.

const TYPES = {
   TYPE: 'type',
   ANOTHER_TYPE: 'anotherType',
}

It is necessary to describe an object that can store functions by keys, which are the values ​​of the TYPES object. That is, this object looks like this:
const object = {
   type: () => {},
   anotherType: () => {},
}

In this case, the task is complicated by the fact that keyof will return the union of keys, and valueof, unfortunately, was not delivered to TS. Having a second object (Object.values(TYPES)) is such an option, because in this case keyof will litter possible keys with various length and other properties and methods built into the Array prototype.
How to solve the problem in the most elegant way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-11-02
@Heian

interface Types {
  TYPE: 'type';
  ANOTHER_TYPE: 'anotherType';
}

type SomeType = {
  [P in Types[keyof Types]]: () => void;
};

const object: SomeType = {
  type: () => {}, 
  anotherType: () => {}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question