繁体   English   中英

typescript - 有没有办法从类型定义创建一个实例

[英]typescript - is there a way to create an instance from type definition

使用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 中,所有类型数据在到达运行时之前都会被删除。

我的问题是 - 我们可以创建一个 object 或符号,它代表运行时的类型吗?

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

我发现一个类似的项目是flow-runtime ,使用babel-plugin-flow-runtime (还有一个 TS 等价物,称为 TS-runtime,但似乎没有开发出来)

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 的项目中尝试了它,结果好坏参半。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM