typescript - 打字稿:有没有办法在不转换为类类型的情况下显示属性和方法?
问题描述
我编写了这段打字稿代码来复制我在项目中遇到的问题。我有一个基类(在本例中为“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
解决方案
正如您可能已经猜到的那样,给定generics
标签,您可以通过创建instantiateFoos
一个通用函数来解决这个问题:
function instantiateFoos<T extends Foo>(fooLikeClass: new () => T) {
return new fooLikeClass();
}
不是fooLikeClass
参数是 type typeof Foo
,而是它是 type new () => T
,一个无参数构造签名,它产生 type 的实例T
,其中T
泛型类型参数被约束为 的子类型Foo
。
现在您的通话可以按需要进行:
let myBar = instantiateFoos(Bar); // let myBar: Bar;
myBar.talk(); // okay
推荐阅读
- javascript - 我正在努力确定选择了哪个下拉元素
- c# - 如何在c#中使用进程类?
- angular - 页面初始加载时显示两个菜单
- c# - Unity C# - 带有 LayerMask 的 Physics.Raycast 方法似乎不会忽略给定的图层
- tensorflow - DQN 的迁移学习
- node.js - nodejs sqlite3 查询返回空 - 无法理解异步
- javascript - 获取响应本机中的php文件时如何修复获取返回404?
- laravel - Laravel Eloquent:有什么方法可以得到改变模型的原始关系?
- c# - Azure Web Job BlobTrigger - 重置 Scaninfo 以触发现有 Blob 的功能
- highcharts - highchart升级后如何修复工具提示