2017-10-11 32 views
3

考慮下面的代碼來檢查數組是否有重複。「集合」僅指一種類型,但在此處用作值。 (TS2693)

let arr: number[] = [1,2,3,1]; 

function hasDuplicates (arr: number[]): boolean { 
    return new Set(arr).size !== arr.length; 
} 

但在這裏我遇到打字稿編譯器錯誤

'Set' only refers to a type, but is being used as a value here. (TS2693) 

有什麼建議?

回答

4

Set作爲ES6的一部分被添加。如果你的目標是ES5或更低,你會得到這個錯誤。

您可以通過升級目標es6tsconfig.json解決這個問題:

"compilerOptions": { 
    "target": "es6", 
    // ... 
} 

或者,如果你不想改變你的目標,但你希望你的代碼編譯添加es6lib選項:

"compilerOptions": { 
    "lib": ["es6"], 
    // ... 
} 

請注意,這種方法如果運行環境不支持Set類,那麼它會拋出一個運行時錯誤。

+0

另外,如果你只需要'es6'庫的設置,你可以使用'es2015.collection'來代替。 –

相關問題