【问题标题】:Typescript static method does not exist on type someclass类型 someclass 上不存在 Typescript 静态方法
【发布时间】:2022-01-17 15:34:39
【问题描述】:

我有这样的代码 -

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 抱怨它在 State1 类中找不到静态方法handlaA()。

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

【问题讨论】:

  • 抱歉,打错了。现在更正它。

标签: javascript typescript static-methods


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    return State1 似乎没有返回您期望的结果。你可以用一个更简单的例子来测试一下:

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

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2023-03-07
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 2011-01-07
      • 1970-01-01
      相关资源
      最近更新 更多