Simon Schneider
Simon Schneider

Reputation: 1236

Mapping classes in typescript

let`s say you want to map a class to a certain React component or any other value using typescript:

import { BooleanField } from "../rendering/components/field/BooleanField";
import { MoneyField } from "../rendering/components/field/MoneyField";
import { TextField } from "../rendering/components/field/TextField";
import BooleanWrapper from "../form/values/BooleanWrapper";
import MoneyWrapper from "../form/values/MoneyWrapper";
import StringWrapper from "../form/values/StringWrapper";

export const fieldComponentsMapping = [
  {
    value: BooleanWrapper,
    component: BooleanField
  },
  {
    value: MoneyWrapper,
    component: MoneyField
  },
  {
    value: StringWrapper,
    component: TextField
  }
];

What would the type of fieldComponentsMapping be?

It is not something like FieldComponentMapping[]:

interface FieldComponentMapping {
  value: ValueWrapper;
  component: StatelessComponent;
}

Since we are not mapping instances to each other but constructors.

Upvotes: 1

Views: 1770

Answers (2)

kingdaro
kingdaro

Reputation: 12018

The way of typing a constructor is to use an interface with a new () key in it. For example, if we had a class named SomeClass, this would be the type of that class, to say that doing new on this creates an instance of that class.

interface SomeClassConstructor {
  new (): SomeClass
}

So, assuming all of your *Wrapper classes extend a ValueWrapper class, here's what it would be:

interface ValueWrapperConstructor {
  new (): ValueWrapper
}

interface FieldComponentMapping {
  value: ValueWrapperConstructor
  component: StatelessComponent
}

Alternatively, this form also works, and looks a little more succinct if you prefer.

type ValueWrapperConstructor = new () => ValueWrapper

https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes

Upvotes: 2

Raphael Schweikert
Raphael Schweikert

Reputation: 18556

I think you can use

interface FieldComponentMapping {
  value: typeof ValueWrapper;
  component: typeof StatelessComponent;
}

typeof will give you the constructor type for class types.

Upvotes: 1

Related Questions