typescript-有没有一种方法可以从类型定义中创建实例

时间:2020-07-14 13:34:05

标签: javascript typescript serialization types

使用打字稿,我试图创建一个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#,其中类型是内存中的(我们不需要)。
在打字稿中,所有打字稿数据在到达运行时之前都会被删除。

我的问题是-我们可以创建一个在运行时表示类型的对象或符号吗?

const mathId = typeToId<IMath>();
// "c8393b569dbae9ed04e5b22d9c2e6fb7"
const mathStub = typeToStub<IMath>();
// { add: () => 0, sub: () => 0 }

1 个答案:

答案 0 :(得分:0)

我发现的一个类似项目是flow-runtime,使用的是babel-plugin-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的我的一个项目中进行了尝试,结果却不尽相同。