1

Is there a way in Typescript to wrap all interface's values into some generic type to get another interface?

I have interface which represents an object with class constructors:

interface MyConstructors {
  foo: typeof Foo;
  bar: typeof Bar;
  // ... etc (many lines here)
}

Then I create instances of these classes:

const instances = {
  foo: new Foo(params),
  bar: new Bar(params)
};

Interface of that object should look like

interface MyInstances {
  foo: InstanceType<typeof Foo>;
  bar: InstanceType<typeof Bar>;
  // ... etc (many lines here)
}

As you can see it looks mostly the same as MyConstructors. So I'm looking for some way to avoid that duplication.

1 Answer 1

7

You can use a mapped type:

type MyInstanceType = {
  [key in keyof MyConstructors]: InstanceType<MyConstructors[key]>
}

// Same as:
// type MyInstanceType = {
//    foo: Foo;
//    bar: Bar;
//}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.