The Prenx
The Prenx

Reputation: 672

Typescript static method does not exist on type someclass

I have code like this -

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

It works perfectly fine, however Typescript complains that it cannot find the static method handlaA() in class State1.

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

Upvotes: 1

Views: 1111

Answers (2)

type StateTypes = State1 | State2 means instance of State1 or State2. What you want is: type StateTypes = typeof State1 | typeof State2. This refers to constructors instead of instances

Upvotes: 3

Kokodoko
Kokodoko

Reputation: 28128

It seems that return State1 does not return what you expect it to. You can test that out in a simpler example:

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

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

Here we hope to get a reference to State1

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

But the error is the same: Property 'test' does not exist on type 'State1'.

You might solve it by making the state an instance. Then you can get a reference to a different state. You can overwrite it with an instance of the new 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()

Upvotes: 0

Related Questions