TypeScript:与构造函数的函数接口
我想要一个行为类似于js Date函数的类:TypeScript:与构造函数的函数接口,typescript,Typescript,我想要一个行为类似于js Date函数的类: 通过new调用时,它会创建类的实例 当作为函数调用时,它会执行一些静态操作 我如何实现这个接口 interface A { (): string; new(arg: number); GetValue(): number; } 当前解决方案未编译,但生成正确的js代码: class B implements A { private Value: number; constructor(arg: numbe
new
调用时,它会创建类的实例interface A {
(): string;
new(arg: number);
GetValue(): number;
}
当前解决方案未编译,但生成正确的js代码:
class B implements A {
private Value: number;
constructor(arg: number) {
if (this.constructor == B) {
this.Value = arg;
} else {
return "42";
}
}
GetValue(): number {
return this.Value;
}
}
在没有new
关键字的情况下,不能使用或类来调用构造函数。在链接文档第9.2.1节的步骤2中,调用不带new
关键字的类构造函数应导致抛出TypeError
。(如果您在TypeScript中以ES5为目标,您将获得运行时有效的功能,但如果您以ES2015或更高版本为目标,您将获得运行时错误。最好不要这样做。)因此,要实现您的接口,您需要使用ES2015之前的构造函数
顺便说一下,new(arg:number)
签名需要返回类型。例如:
interface A {
(): string;
new(arg: number): AInstance; // return something
GetValue(): number;
}
// define the instance type
interface AInstance {
instanceMethod(): void;
}
这里有一种实现方法。首先,为AInstance
创建一个类
:
class _A implements AInstance {
constructor(arg: number) { } // implement
instanceMethod() { } // implement
}
然后,创建一个可以使用或不使用new
调用的函数:
const AFunctionLike =
function(arg?: number): AInstance | string {
if (typeof arg !== "undefined") {
return new _A(arg);
}
return "string";
} as { new(arg: number): AInstance, (): string };
我已经决定,如果您使用参数调用类函数
,那么您将得到一个AInstance
,否则您将得到一个字符串
。如果运行时支持,还可以通过显式检查是否使用了new
还要注意,我必须声明AFunctionLike
是可更新的(最后一行是as
子句),因为目前没有其他方法告诉TypeScript可以使用new
调用独立函数
现在我们差不多完成了。我们可以声明a
类型的值,如下所示:
const A: A = Object.assign(
AFunctionLike,
{
GetValue() {
return 1;
}
}
);
值A
是通过将A类函数
与实现GetValue()
的对象合并而成的。您可以使用或来执行此合并
就这样。您可以验证这在运行时是否有效。祝你好运 在没有new
关键字的情况下,不能使用或类来调用构造函数。在链接文档第9.2.1节的步骤2中,调用不带new
关键字的类构造函数应导致抛出TypeError
。(如果您在TypeScript中以ES5为目标,您将获得运行时有效的功能,但如果您以ES2015或更高版本为目标,您将获得运行时错误。最好不要这样做。)因此,要实现您的接口,您需要使用ES2015之前的构造函数
顺便说一下,new(arg:number)
签名需要返回类型。例如:
interface A {
(): string;
new(arg: number): AInstance; // return something
GetValue(): number;
}
// define the instance type
interface AInstance {
instanceMethod(): void;
}
这里有一种实现方法。首先,为AInstance
创建一个类
:
class _A implements AInstance {
constructor(arg: number) { } // implement
instanceMethod() { } // implement
}
然后,创建一个可以使用或不使用new
调用的函数:
const AFunctionLike =
function(arg?: number): AInstance | string {
if (typeof arg !== "undefined") {
return new _A(arg);
}
return "string";
} as { new(arg: number): AInstance, (): string };
我已经决定,如果您使用参数调用类函数
,那么您将得到一个AInstance
,否则您将得到一个字符串
。如果运行时支持,还可以通过显式检查是否使用了new
还要注意,我必须声明AFunctionLike
是可更新的(最后一行是as
子句),因为目前没有其他方法告诉TypeScript可以使用new
调用独立函数
现在我们差不多完成了。我们可以声明a
类型的值,如下所示:
const A: A = Object.assign(
AFunctionLike,
{
GetValue() {
return 1;
}
}
);
值A
是通过将A类函数
与实现GetValue()
的对象合并而成的。您可以使用或来执行此合并
就这样。您可以验证这在运行时是否有效。祝你好运