[英]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
表示State1
或State2
的實例。 你想要的是: 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.