【发布时间】:2021-10-15 06:47:07
【问题描述】:
我编写了这段打字稿代码来复制我在项目中遇到的问题。我有一个基类(在本例中为“Foo”)和许多从“Foo”扩展的其他类。函数“instanciateFoos”应该能够实例化一个 fooLike 类(在本例中为“Bar”)并以正确的类型返回它。我有很多很长的类名,我很想有一种方法来调用函数,而不必写两次类名。使用我当前的解决方案,我总是必须将返回的对象转换为我已经传递给函数的类,以使打字稿将其识别为类的实例。也许有一些方法可以使用泛型或类似的东西来解决这个问题。
class Foo
{
constructor() { }
}
class Bar extends Foo
{
talk()
{
console.log("Bar");
}
}
function instanciateFoos(fooLikeClass: typeof Foo)
{
return new fooLikeClass();
}
let myBar = instanciateFoos(Bar);
myBar.talk();
// Error: Property 'talk' does not exist on type 'Foo'.ts(2339)
let myBar2 = <Bar>initiateFoos(Bar);
myBar2.talk();
// works
【问题讨论】:
-
举个更好的例子... 在 Unity (C#) 中,您可以像这样向游戏对象添加组件: transform = gameObject.addComponent
();在这里,类名只需要一次,因为泛型在 C# 中是如何工作的(或者至少我是这么认为的)
标签: typescript generics types