在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
类声明同时生成类型和值。该值是类的构造函数(这就是为什么当你在表达式中编写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();
类型所在的值位于不同的域中,因此使用相同的名称就可以了。
不幸的是,没有办法在一个声明中做到这一点,涉及到一些冗长。