在 TypeScript 中将类型作为变量返回

Returning a Type as a Variable in TypeScript

我目前正在用 TypeScript 编写一个 class 工厂,并且想 return 一个类型作为函数的输出。尽管 TypeScript 将类型作为输入来处理——即泛型——很漂亮,我还没有找到一种方法来处理类型作为输出。

提供了一个特别有用的解决方案,但没有完全回答我的问题。鉴于以下结构,

function factory(someVar: any) {
    return class A {
        // Do something with someVar that makes this class unique
    }
}

这个问题表明应该对该工厂函数的输出执行以下操作:

import factory from "someLocation";

const AClass = factory({foo: "bar"});
type A = InstanceType<typeof AClass>;

interface IData {
    someField: A;
}

我有兴趣在我的工厂功能中包含此功能,以使系统更易于重用或模块化。但是,如最初所述,我不确定如何从函数 return 类型。如果我尝试以下操作,TypeScript 会抛出错误 [ts] 'MenuState' only refers to a type, but is being used as a value here. [2693]:

function factory(someVar: any) {
    class AClass {
        // Do something with someVar that makes this class unique
    }

    type A = InstanceType<typeof AClass>;
    return A;
}

我该怎么做?一般来说,是否有任何语义上正确的方法来将类型作为值或变量来处理?如果不是,为什么这违反了 TypeScript 的最佳实践?此外,如果可能的话,如何将此类型用作构造函数?

is there any semantically correct way to handle types as values or variables

没有。类型只是编译时的。将类型表示为值,在 运行 时间可用与语言设计非目标 #5 in this list:

直接矛盾

Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.

唯一的例外是 classes,它们在 运行 时间的表示方式与它们在 es6 javascript 运行 时间的表示方式完全相同:如构造函数。

因此您可以从函数中 return 一个 class,但是该函数将 returning 一个不能用作类型的值。唯一的例外(某种程度上)是您可以使用函数调用表达式而不是 class 作为 extends.

中的基础 class

另外,这个结构

InstanceType<typeof AClass>

被编译器缩减为 AClass,正如在 this type declarationT 的工具提示中所见,其中显示 type T = AClass

type T = InstanceType<typeof AClass>;