简体   繁体   English

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

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

Using Typescript, I am trying to create a DI system, and I want to use the type (or interface ) as the key.使用Typescript,我正在尝试创建一个DI系统,我想使用type (或interface )作为key。

For example,例如,

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

This is is possible in runtime-typed languages, like C#, where types are in-memory (which we don't want).这在运行时类型的语言中是可能的,例如 C#,其中类型在内存中(我们不想要)。
In typescript, all type data is removed before ever reaching runtime.在 typescript 中,所有类型数据在到达运行时之前都会被删除。

My question is - can we create an object or symbol, that will represent the type during runtime?我的问题是 - 我们可以创建一个 object 或符号,它代表运行时的类型吗?

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

A similar project I found was flow-runtime , using babel-plugin-flow-runtime .我发现一个类似的项目是flow-runtime ,使用babel-plugin-flow-runtime (There's also a TS equivalent called TS-runtime, but it doesn't seem as developed) (还有一个 TS 等价物,称为 TS-runtime,但似乎没有开发出来)

type User = {
  id: number;
  name: string;
};

transforms into转变为

import t from 'flow-runtime';
const User = t.type('User', t.object(
  t.property('id', t.number()),
  t.property('name', t.string())
));

This seems like an overkill, both in bundle size and performance.无论是在捆绑包大小和性能方面,这似乎都是一种矫枉过正。
I also tried it in one of my projects still using Flow, and it's giving mixed results.我还在我的一个仍在使用 Flow 的项目中尝试了它,结果好坏参半。

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

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