TypeScript构造函数重载返回不同的类型

时间:2018-06-10 04:21:16

标签: typescript

我有一个构造函数,应该根据param返回不同的类型。

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);

但它不起作用。我该怎么做?

1 个答案:

答案 0 :(得分:2)

您无法直接定义此类。您可以定义常规类并将其重命名为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
相关问题