Ondra Žižka Ondra Žižka - 4 months ago 34
TypeScript Question

TypeScript - storing a class as a map value?

I have few classes.

Test~
classes extend
FrameModel
.

How can I create a map from
string
to subclasses of
FrameModel
?

import FrameModel from '../../FrameModel';
import TestShipModel from './TestGeneratorModel';
import TestGeneratorModel from './TestGeneratorModel';
import TestPlanetModel from './TestGeneratorModel';

export class DiscriminatorMappingData
{
static mapping: { [key: string]: typeof FrameModel } = {
"TestShip": TestShipModel,
"TestGenerator": TestGeneratorModel,
"TestPlanet": TestPlanetModel,
}
}


This ends up with an error:

DiscriminatorMappingData.ts(8,5): error TS2322: Type '{ [x: string]: typeof "...' is not assignable to type '{ [key: string]: typeof "...'.

Index signatures are incompatible.

Type 'typeof "...models/T...' is not assignable to type 'typeof ".../FrameModel"'.

Property 'FrameModel' is missing in type 'typeof ".../models/T...'.

I assume this can be done with generics but I'm not sure how.

Answer

(With reference to the comment, here is the solution to the problem.)

The problem seems to be with the import statement and curly brackets should be included while importing class. e.g. import {FrameModel}...