TypeScript - 将类存储为映射值? [英] TypeScript - storing a class as a map value?
问题描述
我有几个课程。 测试〜
类扩展 FrameModel
。
I have few classes. Test~
classes extend FrameModel
.
如何创建一个从 string
到 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,
}
}
$ b b
这会导致错误:
This ends up with an error:
DiscriminatorMappingData.ts(8,5):error TS2322:Type'{[x:string]:typeof。 ..'无法分配给类型{[key:string]:typeof...。
索引签名不兼容。
键入'typeof'... models / T ...'不能分配给类型'typeof'... / FrameModel'。
类型'typeof'中缺少属性'FrameModel'... / models / T ... '。
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.
推荐答案
(参考意见,这里是问题的解决方案。)
(With reference to the comment, here is the solution to the problem.)
与导入类时应包含 import
语句和大括号。例如 import {FrameModel} ...
The problem seems to be with the import
statement and curly brackets should be included while importing class. e.g. import {FrameModel}...
这篇关于TypeScript - 将类存储为映射值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!