繁体   English   中英

Typescript static 方法在 someclass 类型上不存在

[英]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 中找不到 static 方法handlaA()。

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

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

似乎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'.

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM