刚接触 typescript,如何将类通过方法导出?

2020-02-03 12:40:57 +08:00
 zy445566
type ClassA = class aaa{}
function getClassA():typeof ClassA {
	return ClassA
}

主要是为了统一入口动态导出类,但发现这样在另一个文件 Promise<classa>报,把值作为类使用。各位大佬怎么搞?</classa>

3320 次点击
所在节点    程序员
21 条回复
noe132
2020-02-04 09:57:44 +08:00
要分清楚类型和值

class A {}
const a = new A()

其中 a 是值,代表 A 的实例
A 既是值也是类型,作为值的时候代表 A 本身,作为类型时代表 A 的实例类型
A(值)本身的类型呢? typeof A
怎么通过类的类型获取实例类型? InstanceType<T>

class A {}
const a: A = new A();

type AClassType = typeof A // 类的类型
const B: AClassType = A;
const a2: A = new B();
const a3: InstanceType<AClassType> = new A();

type Factory = () => A;
const factory: Factory = () => new A();

type Factory2 = <T extends { new(...p: any): any }>(c: T) => InstanceType<T>;
const factory2: Factory2 = (C) => new C();

const a4: A = factory2(A);

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/641806

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX