【发布时间】:2021-07-07 03:59:41
【问题描述】:
我正在研究将函数的返回类型定义为实现接口的类型的可能性
不是实现接口的类型的实例,类型本身
我可以做的类型:
interface A {
doSomething(): number;
}
class Base implements A {
doSomething() { return 1; }
}
class Ext1 extends Base {
doSomething() { return 2; }
}
class Ext2 extends Base {
doSomething() { return 3; }
}
function process(x: number): typeof Base | null {
if (x === 1) {
return Ext1;
} else if (x === 2) {
return Ext2;
}
return null;
}
根据条件,您的正常工厂功能是什么
问题是,我必须定义我根本不关心的Base 类并做一些A 的虚拟实现
我正在寻找的是:
interface A {
doSomething(): number;
}
class Ext1 implements A {
doSomething() { return 2; }
}
class Ext2 implements A {
doSomething() { return 3; }
}
function process(x: number): typeof A | null {
if (x === 1) {
return Ext1;
} else if (x === 2) {
return Ext2;
}
return null;
}
但发生错误
'A' only refers to a type, but is being used as a value here.ts(2693)
有没有办法做到这一点?
【问题讨论】:
标签: typescript