我有這樣的代碼 -
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'.
uj5u.com熱心網友回復:
type StateTypes = State1 | State2State1表示or的實體State2。你想要的是:type StateTypes = typeof State1 | typeof State2. 這指的是建構式而不是實體
uj5u.com熱心網友回復:
似乎這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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414490.html
標籤:
