我仍然在思考泛型类,我需要动态创建其他类。但我不知道该怎么做。
Class A {}
Class B<T> {
Return T
}
Const c = B(A); // which is T
提供更多有关我正在尝试做的事情的背景信息。
我使用 angular 和 typescript 3.45。通过解析正确的组件动态创建表单。在指令中,我应该能够检索一个泛型类。并在不知道它正在创建的类的情况下使用它。遵循关注点分离。
更新
最后我得到了通用类型的一部分,但仍然有一些灰色区域我仍在挣扎并且不确定从哪里开始。对于任何有兴趣但可能有点困惑的人,我希望这会有助于给你一些澄清。
采用任何输入类型并接收相同的类型。代码示例,让我们将此泛型类型称为 U
。
function func(a: U): U {
return a;
}
const c = func(arg: U); // after this line, c has a value of type U
// Same as
const c = func(10); // now c = 10;
我想问的是,对于任何输入类型,我都会得到一个通用类型作为返回类型。这很愚蠢,因为编译器从输入中推断类型并将 U 替换为实际的自定义或原始类型。
对于我的返回泛型类型,也许我们可以通过条件类型来实现它,但我仍然在使用整个类型,转换类型和隐藏类型隐藏在扩展和实现之后。 link
感谢您的回答,这是我当前问题的正确答案。
最佳答案
如何在 TypeScript 中实例化泛型
来源 Rico Suter 的 博客。 link
But how would you write such a method in
TypeScript
? The main problem is, that the generic type argument T is not available at runtime becauseTypeScript generics
are only used at compile time for type checking and removed in the transpiledJavaScript
code.
public class YourFactory
{
public T Create<T>()
where T: new()
{
return new T();
}
}
var yourFactory = new YourFactory();
var person = yourFactory.Create<PersonModal>();
引用this
关于javascript - typescript 创建一个类隐藏其他类并返回通用结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946327/