網站搜尋

如果有兩個相似的類別,TypeScript 無法推斷方法的類型


TypeScript 遊樂場

class A {
    constructor(m: B | C) {}
}

class B {
    foo() {
        return new A(this);
    }
}

class C {
    foo() {
        return new A(this);
    }
}

B.foo() 的返回類型正確解析為 A,但 C.foo() 是 any:

'foo' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

如果你將 m 的類型改為 C | B,B.foo() 會返回 any 而 C.foo() 會返回 A。如果你讓 B 和 C 之間有一些明顯的區別,使得 B 擁有 C 沒有的東西(但反過來不成立),它們都會正確解析。

這對我來說有點令人困惑。