typescript - Typescript:从函数的返回中定义类类型(并将其用作类型)
问题描述
有没有办法从函数的返回中定义一个类,然后将其用作接口中的属性类型?
class Foo {};
function makeFoo<T extends Foo>(classType: T): T {
return classType;
}
const Foo2 = makeFoo(Foo);
new Foo(); // OK
new Foo2(); // OK
interface IFoo {
foo1: Foo; // OK
foo2: Foo2; // 'Foo2' refers to a value, but is being used as a type here.
}
真实世界的用例是我有一个函数,它使用类的泛型类型向类添加一些静态方法。所以,
class DataModel {}
class Foo<T extends DataModel> {}
class Bar extends Foo<DataModel> {
getInstance() {
return 'I am an instance';
}
}
function addStatics<T extends DataModel, TF extends Foo<T>>(
classType: TF,
): TF & { getStatic: () => T } {
return Object.defineProperty(classType, 'getStatic', {
value: () => {},
});
}
// This is: typeof Bar & { getStatic: () => typeof DataModel; }
const BarWithStatics = addStatics(Bar);
console.log(BarWithStatics.getStatic(), new BarWithStatics().getInstance());
实际上,它正在使用单例实例做一些事情,但是,是的,这就是它的要点。我希望有一些方法可以做,class BarWithStatics = addStatics(Bar)
但没有这样的运气。
解决方案
当然,一旦我提出这个问题,我就会找到解决方案。您可以扩展函数的返回:
class BarWithStatics extends addStatics(Bar) {}
interface IFoo {
bar: BarWithStatics;
}
推荐阅读
- android - 有没有办法用 kotlin 扩展覆盖函数
- flutter - 如何在 sqflite 中进行操作(插入、更新、删除、查询)将外部数据库导入颤振?
- javascript - 在 Dynamics 365 中隐藏多选选项集字段
- django - 有没有办法在 Django 过滤器中优先考虑某些对象?
- linux - 2 个网络服务器的 Linux Haproxy 负载均衡器 haproxy.cfg 语法
- angularjs - 如何使用 ng-repeat 在 angularjs 中动态禁用单选按钮
- django - 填充表单时相关对象不存在
- angular - 如何在 Typescript 中强制重新加载和清除缓存?
- c - cJSON_Delete() 和 cJSON_free()
- javascript - 按表类选择一个 td