2016-10-31 61 views
25

我有一個類型:如何禁止TypeScript「錯誤TS2533:對象可能是'null'或'undefined'」?

type tSelectProtected = { 
    handleSelector?: string, 
    data?: tSelectDataItem[], 

    wrapperEle?: HTMLElement, 
    inputEle?: HTMLElement, 
    listEle?: HTMLElement, 
    resultEle?: HTMLElement, 

    maxVisibleListItems?: number 
} 

我宣佈一個全球性的 - 模塊明智 - 變量:

var $protected : tSelectProtected = {}; 

我指定的功能1範圍適當的值:

$protected.listEle = document.createElement('DIV'); 

我m函數,稍後在函數2範圍內:

$protected.listEle.classList.add('visible'); 

我得到打字稿錯誤:

error TS2533: Object is possibly 'null' or 'undefined' 

我知道我可以使用if ($protected.listEle) {$protected.listEle}冷靜下來編譯器做明確的檢查,但這似乎是最不平凡的情況非常不方便。

如何在不禁用TS編譯器檢查的情況下處理這種情況?

回答

8

此功能稱爲「嚴格空檢查」,將其關閉以確保--strictNullChecks編譯器標誌未設置。

但是,null的存在been describedThe Billion Dollar Mistake,因此看到TypeScript等語言引入修復程序令人興奮。我強烈建議保持打開狀態。解決這個問題

的一種方法是,以確保值是從來沒有nullundefined,例如通過初始化它們前面:

interface SelectProtected { 
    readonly wrapperElement: HTMLDivElement; 
    readonly inputElement: HTMLInputElement; 
} 

const selectProtected: SelectProtected = { 
    wrapperElement: document.createElement("div"), 
    inputElement: document.createElement("input") 
}; 
+1

我個人使用「vanilla」JavaScript中的'null'來初始化變量或屬性值。這給了我直接的答案,如果給定var或prop存在,但它「沒有可用值」或「在某個執行點清除了值」。這只是慣例。這可能不是TypeScript中的最佳方法,正如我在這裏可以看到的答案。謝謝你的想法。 – grasnal

5

如果您知道類型永遠不會是nullundefined,您應該聲明它爲foo: Bar而不是?。使用? Bar語法聲明類型意味着它可能未定義,這是您需要檢查的內容。

換句話說,編譯器正在按照您的要求進行操作。如果你希望它是可選的,你將需要稍後檢查。

+0

「編譯器做你的要求正是它的」 所以我的想法是錯了,謝謝。我需要改變一點。 – grasnal

104

如果從外部手段知道表達式的值不是nullundefined ,您可以使用非空斷言運營商!強迫離開這些類型:

// Error, some.expr may be null or undefined 
let x = some.expr.thing; 
// OK 
let y = some.expr!.thing; 
+0

謝謝你讓我知道'! - 非空斷言運算符運算符。它似乎還沒有很好的文檔([https://github.com/Microsoft/TypeScript/issues/11494](https://github.com/Microsoft/TypeScript/issues/11494)),所以任何尋找答案的人閱讀本文[http://stackoverflow.com/questions/38874928/operator-in-typescript-after-object-method](http://stackoverflow.com/questions/38874928/operator-in-typescript-after-object-方法) – grasnal

+0

謝謝你的回答。 – skiabox

+0

謝謝你 - 這應該是我接受的答案 – user1859022

2

該解決方案爲我工作:

  • 轉至tsconfig。JSON並添加「strictNullChecks」:假

enter image description here

+0

這也適用於我。 雖然它仍然給出錯誤,例如在訂閱語句中,它不會識別結果變量,打字稿要它聲明 .subscribe(result => this.result = result.json()); – Aarchie

+0

您是否嘗試過使用「地圖」運算符? Google'rxjs/map'。我基本上是這樣做的。 Http.get(...)。map(result => result.json())。subscribe(result => {do your stuff here}) –

1

我用:

if(object !== undefined){ // continue - error supressed when used in this way. }

相關問題