2016-11-10 136 views
3

我一直在使用tslint相當一段時間no-null-keyword啓用。最近,我已升級到Typescript 2.0並啓用--strictNullChecking。但是,查看Typescript的lib.d.ts,看起來不可能保持no-null-keyword啓用(乍一看),因爲某些調用的結果可能是null。例如:tslint沒有null關鍵字和打字稿的lib.d.ts與嚴格的空檢查

const result: RegExpExecArray | null = regex.exec(regexStr); 

if (result === null) { // <-- tslint complains about this check 
    throw new Error("Foo location: result of regex is null."); 
} 

// or 
// if (result !== null) { 
//  ...do something 
// } 

的問題是什麼是的右 - 事物 - 待辦事項

Disable no-null-keyword for tslint

使用黑客(?):

const result: RegExpExecArray = regex.exec(regexStr)!; 

if (result == undefined) { // Will check if result is undefined or null 
    throw new Error("Foo location: result of regex is null."); 
} 

或者其他什麼東西?

回答

2

no-null-keyword只是一個不起眼的規則。它的主要目的是防止你使用undefined和null這兩個常常相似目的的複雜性。

但它並沒有將它移除到供應商的代碼庫中,而是在很多庫中使用它。

result == undefined確實是一個完全有效的JS成語,如果你需要檢查空值和未定義的值。這不被視爲黑客(AFAIK),並且比簡單但危險的Falsy檢查更受歡迎:if (!result) {..}

tslint甚至允許一個例外爲其===規則:

"triple-equals": [true, "allow-undefined-check"]

+0

是的,這正是我在做自從我提出這樣的問題: '「三平等」:真「 allow-undefined-check「]' 代碼爲'foo == undefined'或'foo!= undefined'以及一個適當的註釋來澄清原因。 – vladeck