[英]Using spread syntax and new Set() with typescript
我正在使用以下代碼來獲取唯一編號:
let uniques = [ ...new Set([1, 2, 3, 1, 1]) ]; // [1, 2, 3]
但是,打字稿報告以下錯誤: Type 'Set' is not an array type。 我不是打字稿忍者,有人能告訴我這里有什么問題嗎?
更新:使用 Typescript 2.3,您現在可以將"downlevelIteration": true
downlevelIteration "downlevelIteration": true
添加到您的 tsconfig,這將在面向 ES5 時起作用。
的缺點downlevelIteration
是TS將有transpiling時注入相當多的樣板。 問題中的單行轉換為 21 行添加的樣板:(從 Typescript 2.6.1 開始)
var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; var uniques = __spread(new Set([1, 2, 3, 1, 1])); console.log(uniques);
這個樣板將在每個使用下級迭代的文件中注入一次,並且可以通過"importHelpers"
使用"importHelpers"
選項減少這個樣板。 (請參閱有關importHelpers
迭代和importHelpers
博客importHelpers
)
或者,如果 ES5 支持對您來說無關緊要,您始終可以首先定位“es6”,在這種情況下,原始代碼無需“downlevelIteration”標志即可工作。
原答案:
這似乎是一個打字稿 ES6 轉譯的怪癖。 ...
運算符應該適用於任何具有迭代器屬性的東西,(由obj[Symbol.iterator]
訪問)並且集合具有該屬性。
要解決此問題,您可以先使用Array.from
將集合轉換為數組: ...Array.from(new Set([1, 2, 3, 1, 1]))
。
您還可以使用 Array.from 方法將 Set 轉換為 Array
let uniques = Array.from(new Set([1, 2, 3, 1, 1])) ; console.log(uniques);
這是一個缺失的功能。 TypeScript 目前僅支持數組上的可迭代對象。
在 JavaScript 中:
[ ...new Set([1, 2, 3, 1, 1]) ]
在打字稿中:
Array.from(new Set([1, 2, 3, 1, 1]))
在反應狀態(setState)中:
setCart(Array.from(new Set([...cart, {title: 'Sample', price: 20}])));
您需要在"target": "es6",
設置"target": "es6",
。
要使其工作,您需要在 tsconfig.json 的 compilerOptions 中使用 "target": "ES6"(或更高版本)或 "downlevelIteration": true。 這解決了我的問題並且工作良好或我。希望它也能幫助你。
現在,您可以在 Typescript 設置中使用Set
(無需定位es6
):
在您tsconfig.json
,添加以下行:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
},
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.