【发布时间】:2020-11-03 20:45:28
【问题描述】:
使用Typescript,我正在尝试创建一个DI系统,我想使用type(或interface)作为key。
例如,
interface IMath {
add: (a: number, b: number) => number;
sub: (a: number, b: number) => number;
}
class Math implements IMath {
add(a: number, b: number) { return a + b };
sub(a: number, b: number) { return a - b };
}
di.register(IMath, Math); // of course this doesn't work
这在运行时类型的语言中是可能的,比如 C#,其中类型在内存中(我们不想要)。
在 typescript 中,所有类型数据在到达运行时之前都会被删除。
我的问题是 - 我们可以创建一个对象或符号,在运行时代表类型吗?
const mathId = typeToId<IMath>();
// "c8393b569dbae9ed04e5b22d9c2e6fb7"
const mathStub = typeToStub<IMath>();
// { add: () => 0, sub: () => 0 }
【问题讨论】:
标签: javascript typescript serialization types