[英]Do TypeScript and typescript-eslint have overlapping purposes?
我正在閱讀typescript-eslint文檔,然后進入了這一部分:
TypeScript 和 ESLint 有相似的用途
這意味着在某些情況下,TypeScript 實際上為我們解決了以前依賴 ESLint 的問題。
考慮到它們的定義,一種是靜態類型語言,一種是解析代碼並放置一些斷言以確保考慮某些規則和模式的工具,這是完全不同的東西。 我想知道可以給出哪些示例來solves a problem for us that we previously relied on ESLint for
。 這兩件事有什么共同點嗎? 它們的相似目的是什么?
由於 JavaScript 是一種動態類型語言,因此與使用編譯器處理常見問題的靜態語言相比,程序員可以更輕松地引入細微的錯誤和錯誤,這些錯誤和錯誤在運行時會失敗。
以下面的代碼為例:
console.log(someUndefinedVariable)
const constant = 0
constant = 3
const addOne = n => {
if (typeof n !== 'nubmer') {
throw new Error('n must be an number')
console.log('This will never be executed')
}
if (n < 0) console.log('negative number')
else return n + 1
}
console.log(addOne(-3) * 2)
const symbol = new Symbol()
此代碼將在運行時失敗,並且還有一些其他可能導致意外結果的問題。
諸如 ESLint 之類的 Linter 通過諸如 no-undef 和 no const-assign 之類的規則來解決其中的一些問題:
1:13 error 'someUndefinedVariable' is not defined no-undef
4:1 error 'constant' is constant no-const-assign
7:20 error Invalid typeof comparison value valid-typeof
9:3 error Unreachable code no-unreachable
16:20 error `Symbol` cannot be called as a constructor no-new-symbol
同樣,TypeScript 的編譯器也會就以下許多問題向您發出警告:
Cannot find name 'someUndefinedVariable'.
Cannot assign to 'constant' because it is a constant.
This condition will always return 'true' since the types
'"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"'
and '"nubmer"' have no overlap.
Unreachable code detected.
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
從這個意義上說,ESLint 和 TypeScript 有相同的目標:通過事先警告你來防止可能的程序員錯誤。 對於這些問題,您可以關閉相應的 ESLint 規則並改用 TypeScript 編譯器。
然而,TypeScript 最重要的特性是它向 JavaScript 添加了靜態類型。 通過向addOne
添加類型注釋:
const addOne = (n: number): number => { /* ... */ }
TS 告訴我們, Function lacks ending return statement and return type does not include 'undefined'.
因為如果n
是負數,函數將返回undefined
而不是數字。 addOne(-3) * 2
將是NaN
,而不是像預期的-4
。
另一個例子,ESLint 完全可以使用但在運行時失敗:
const foo = 0
const bar = foo()
// ~~~
// This expression is not callable.
// Type 'Number' has no call signatures.
由於 TypeScript 的類型系統,這些是 TypeScript 可以幫助識別的許多問題中的一些。
另一方面,包括 ESLint 和 typescript-eslint 插件在內的 linter 可以強制執行最佳實踐,例如使用嚴格相等運算符和正確處理 promises 。 它們還可以強制執行樣式約定,例如縮進、 要求或禁止分號或一致的類型斷言樣式。
TypeScript 和 ESLint 具有防止程序員錯誤和錯誤的相似目標。 然而,由於它的類型系統,TypeScript 可以發現更多的運行時和編程錯誤,而 ESLint 可以強制執行風格約定和最佳實踐。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.