【问题标题】:typescript - is there a way to create an instance from type definition打字稿 - 有没有办法从类型定义创建一个实例
【发布时间】: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


    【解决方案1】:

    我发现一个类似的项目是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 的项目中进行了尝试,结果好坏参半。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多