类型 someclass 上不存在 Typescript 静态方法

Typescript static method does not exist on type someclass

我有这样的代码 -

type StateTypes = State1 | State2;
    
class State1 { 
    static handleA (): StateTypes { 
        // Do Something
        return State2; 
    }
    static handleB (): StateTypes {
        // Do Something
        return State1;
    }
}

class State2 { 
    static handleA (): StateTypes { 
        // Do Something
        return State1; 
    }
    static handleB (): StateTypes {
        // Do Something
        return State2;
    }
}


let currentState: StateTypes = State1;

for (/* some Condition*/){
    if(/* some Condition*/)
        currentState = currentState.handleA();
    else
        currentState = currentState.handleB();
}

它工作得很好,但是 Typescript 抱怨它无法在 class State1 中找到静态方法 handlaA()。

TS2339: Property 'handleA' does not exist on type 'StateTypes'.   Property 'handleA' does not exist on type 'State1'.

似乎 return State1 没有 return 您期望的那样。您可以在一个更简单的示例中进行测试:

class State2 { 
    static handleB (): State1 {
        return State1
    }
}

class State1 { 
    static test (): void {
        console.log("testing")
    }
}

这里希望得到State1的引用

let currentState = State2.handleB()
currentState.test()

但是错误是一样的:Property 'test' does not exist on type 'State1'.

您可以通过将状态设为实例来解决它。然后您可以获得对不同状态的引用。您可以用新状态的实例覆盖它。

type currentState = State1 | State2

class State2 { 
    getNewState (): State1 {
        return new State1()
    }
    testMessage (): void {
        console.log("state two")
    }
}

class State1 { 
    getNewState (): State2 {
        return new State2()
    }
    testMessage (): void {
        console.log("state one")
    }
}


let currentState = new State2()

// ask for the new state 
currentState = currentState.getNewState()
currentState.testMessage()

type StateTypes = State1 | State2 表示 State1State2 的实例。 你想要的是:type StateTypes = typeof State1 | typeof State2。这是指构造函数而不是实例