我有一个构造函数,它应该根据参数返回不同的类型。
interface B {
hello(): string;
}
class Foo {
constructor(withB: boolean): Foo & B;
constructor();
constructor(withB?: boolean) {
if (withB) {
Object.assign(this, { hello() {}})
}
}
}
const foo1 = new Foo();
const foo3 = new Foo(true);
但它不起作用。我该怎么做?
您不能直接定义这样的类。您可以定义常规类并将其重命名为FooImpl
并声明一个常量,该常量表示具有 dirrent 重载的构造函数并将其分配FooImpl
给它:
interface B {
hello(): string;
}
class FooImpl {
constructor(withB?: boolean) {
if (withB) {
Object.assign(this, { hello() {}})
}
}
}
const Foo : {
new(withB: boolean): FooImpl & B;
new() : FooImpl;
}= FooImpl as any;
const foo1 = new Foo(); // FooImpl
const foo3 = new Foo(true); // FooImpl & B
如果您的接口只有方法,您也可以避免使用泛型并this
在接口方法上指定参数,将它们的可见性限制为该类型的某些参数:
interface B {
hello(): string;
}
class Foo<T=void> {
private withB: T;
constructor(withB: T) ;
constructor();
constructor(withB?: boolean) {
}
hello(this: Foo<boolean>): string {
return "";
}
}
const foo1 = new Foo();
foo1.hello() // Invalid
const foo3 = new Foo(true);
foo3.hello() // Valid
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句