TypeScript 中是否有等效的 Array.from()
?
或者,有没有办法使用浏览器中的 Array.from()
实现?
我正在尝试将 NodeList 转换为数组以便使用数组方法。
这就是我要用 vanilla JavaScript 做的事情:
const divs = document.querySelectorAll('div');
const arrDivs = Array.from(divs);
const result = arrDivs.map(e => {...});
Array.from()
在 TypeScript 中不可用,它有自己的 Array
实现。
所以我认为我必须像这样将其转换为 Element[]
或 HTMLElement[]
:
const arrDivs = <HTMLElement[]>divs;
但随后出现以下错误:
Conversion of type 'NodeListOf' to type 'HTMLElement[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'NodeListOf' is missing the following properties from type 'HTMLElement[]': pop, push, concat, join, and 14 more.
所以我必须先将 NodeList 转换为 unknown
,然后再转换为 HTMLElement[]
:
const arrDivs = <HTMLElement[]><unknown>divs;
这似乎无视了 TypeScript 固有的类型安全性。所以我想知道是否有更好或更正确的方法来做到这一点?或者以某种方式调用现代浏览器中的原生 Array.from()
函数?
更新
我的编译器告诉我 Property 'from' does not exist on type 'ArrayConstructor'。
这是我的编译器选项:
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
// Linting rules:
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
}
最佳答案
确保您在 tsconfig.json
中以 ES2015 或更高版本为目标:
"compilerOptions": {
"target": "es2015"
}
当您省略该字段时,it defaults to "es3"
这是一个 JS 版本,Array.from
不是一个东西。
关于javascript - 相当于 Array.from() 的 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61208954/