使用Typescript,我正在尝试创建一个DI系统,并且我想使用type (或interface)作为密钥。
例如,
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 }发布于 2020-07-14 21:49:47
我发现的一个类似的项目是使用babel-plugin-flow-runtime的flow-runtime。(还有一个被称为TS-runtime的TS等价物,但它看起来并不成熟)
type User = {
id: number;
name: string;
};转换为
import t from 'flow-runtime';
const User = t.type('User', t.object(
t.property('id', t.number()),
t.property('name', t.string())
));无论是在捆绑包大小还是性能上,这似乎都是一种过度的杀伤力。
我还在我的一个项目中尝试了它,仍然使用Flow,它给出了好坏参半的结果。
https://stackoverflow.com/questions/62896455
复制相似问题