G
G
GF2020-10-24 11:58:38
typescript
GF, 2020-10-24 11:58:38

How to expand union to interface?

You can turn an interface into a union using [K in keyof T], but how to iterate over each member of the union?
Expected Behavior

type union = 'a' | 'b' | 'c'
interface I {
  [здесь пройтись циклом по каждому мемберу из union]: any
}
// result:
interface I {
a: any
b: any
c: any
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2020-10-24
@fomenkogregory

type Union = 'a' | 'b' | 'c';
type Obj = {
  [K in Union]: any;
};
As far as I remember, this is not possible with the interface

D
Demian Smith, 2020-10-24
@search

You probably meant this:

type union = 'a' | 'b' | 'c'
type I = {
  someOtherField?: number;
} & Record<union, any>;
// result:
interface I {
  someOtherField?: number;
  a: any
  b: any
  c: any
}

If you don't need additional fields in the interface (like someOtherFieldthe one in the example), then you can get away with just Record<union, string>. Something like this:
type I = Record<union, any>;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question