我正在嘗試使用callAction動態呼叫類方法的方法創建一個抽象類。
我試圖寫這個,但我得到了錯誤。
abstract export class BaseContoller {
public callAction(method: keyof typeof this, parameters: any[]) {
this[method](parameters);
}
}
錯誤 - 此運算式不可呼叫。型別“未知”沒有呼叫簽名。ts(2349)
還有另一種方法可以實作這一目標嗎?
uj5u.com熱心網友回復:
您的類可以同時具有值??和函式屬性,因此要確保您的屬性是函式型別,您可以使用typeof x === "function".
這有助于method在方法執行之前使用呼叫簽名檢查 's 型別。
class BaseContoller {
public callAction(method: keyof typeof this, parameters: any[]) {
const property = this[method]
if(typeof property === "function") {
property(parameters);
}
}
public testFunction() {}
}
操場
uj5u.com熱心網友回復:
我認為靜態代碼驗證不可能在編譯時知道所涉及的子類。this因此,除非您完全放棄型別檢查并首先轉換,否則您不能這樣做any。
相反,如果您想要 Typescript 的型別檢查的好處,我認為您將不得不接受直接呼叫您的子類方法的其他代碼。
在運行時斷言型別安全可能更聰明。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524584.html
