typescript - 如何使用“typeof”从泛型类中获取类型?
问题描述
A
当我在中声明一个泛型类a.js
,并导出它。然后,我不知道如何在中声明类的A
变量b.js
。
下面的代码
a.js
::
export let A = function<K extends { value: number }>(DEFAULT_NUMBER){
return class A<T> {
test(obj: T, num: number): K {
return obj.diff(DEFAULT_NUMBER, num);
};
};
}(
// DEFAULT_NUMBER
1000
);
b.js
import { A } from "a.js";
class B {
diff(): { value: number } {
// ...
}
};
let a: InstanceType<typeof A<B>> = new A();
a.test(new B(), 50);
下面更简单的代码:
let A = class<T> {};
class B {};
let a: InstanceType<typeof A<B>>; // throw a syntax error
// or
let a: InstanceType<(typeof A)<B>>; // throw a syntax error
// or
let a: InstanceType<typeof (A<B>)>; // throw a syntax error
// or
let a: (InstanceType<typeof A>)<B>; // throw a syntax error
// or
let a: InstanceType<typeof A>; // correct, but the type of a is `A<unknown>`
我应该如何声明变量a
?
解决方案
我认为这没有语法。获取具有特定类型参数的泛型函数的返回类型当然没有语法。
一种方法是通过一个虚拟函数:
let A = class<T> {};
class B {};
let aHelper = () => new A<B>();
let a: ReturnType<typeof aHelper>;
推荐阅读
- java - 通过休息服务检查数据库表的每条记录
- node.js - Typescript NodeJs 解决方案拆分为多个项目
- java - 原因:java.lang.IllegalStateException:计时器已取消。:Oracle 数据库
- javascript - Mozilla Firefox 和 Material-UI 之间出现这种视觉问题的根本原因是什么?
- java - 如何在任何 Java Spring MVC 代码中调用水平菜单?Java Spring MVC 中是否有 php 的 include_once 类似物?
- javascript - TypeError: require(...).collection 不是 Object 的函数。
- javascript - 验证并返回红色
- javascript - 在 React JS 的子组件中,道具的价值没有体现
- java - 请求处理失败;嵌套异常是 java.lang.ClassCastException:java.util.LinkedHashMap 无法转换为 MyClass
- django - 我是 Celery 和 Django 的新手,如何将 celery 响应的所有结果存储在一个文本文件中