首页 > 解决方案 > 如何使用“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

标签: typescript

解决方案


我认为这没有语法。获取具有特定类型参数的泛型函数的返回类型当然没有语法。

一种方法是通过一个虚拟函数:

let A = class<T> {};

class B {};

let aHelper = () => new A<B>();
let a: ReturnType<typeof aHelper>;

推荐阅读