如何正确键入在TypeScript中返回类的函数?

时间:2019-04-11 15:47:39

标签: typescript

在TypeScript中,class关键字同时引入了值和类型:

class Plain { };
const plain: Plain = new Plain();

有没有办法使函数返回既是类型又是值的东西?

问这个问题的另一种方法是:是否可以在下面声明createClass的类型,以便进行const a2: Animal = new Animal()的类型检查?

declare function createClass<T extends string>(t: T): (new () => { type: T });

const Animal = createClass("animal");

const a1         = new Animal();
const a2: Animal = new Animal(); // Error: 'Animal' refers to a value, but is being used as a type here.
const a3: InstanceType<typeof Animal> = new Animal(); // OK but verbose, even if I make a type alias

See this TypeScript Playground

1 个答案:

答案 0 :(得分:2)

类声明同时产生类型和值。值是该类的构造函数(这就是为什么在表达式中编写new Plain()时调用了构造函数的原因)。该类型与该类具有相同的名称,并表示该类的实例类型(这就是为什么您可以在类型注释中使用它的原因)

另一方面,const只是一个值,即使它确实包含一个类。没有相应的类型。实现与类声明相似的功能的唯一方法是创建一个具有相同名称的类型别名。

declare function createClass<T extends string>(t: T): (new () => { type: T });

const Animal = createClass("animal");
type Animal = InstanceType<typeof Animal>

const a1         = new Animal(); 
const a2: Animal = new Animal(); 

类型的值位于不同的域中,因此可以使用相同的名称。

不幸的是,没有一个方法可以做到这一点,涉及到一些冗长的细节。