我有一个构造函数,它应该根据参数返回不同的类型。
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);
Run Code Online (Sandbox Code Playgroud)
但它不起作用。我该怎么做?
您不能直接定义这样的类。您可以定义常规类并将其重命名为,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
Run Code Online (Sandbox Code Playgroud)
如果您的接口只有方法,您也可以摆脱泛型并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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1349 次 |
| 最近记录: |