javascript - 相当于 Array.from() 的 TypeScript

标签 javascript arrays typescript dom

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/

相关文章:

typescript - 使用镜头和遍历获取部分对象并返回 "filled in"对象的函数式编程/光学概念?

javascript - 有没有浏览器键盘绑定(bind)的开源库JS?

php - 我如何从 array() 中删除它?

javascript - 数组到对象的数组 - javascript

python - 使用来自 (x,y,value) 三元组的数据创建 Numpy 二维数组

typescript - Angular2、TypeScript 和 Visual Studio Code 绝对路径配置

javascript - 无法获得在华氏温度和摄氏温度之间切换的按钮

javascript - 选择 capybara 验收测试

javascript - WebSocket - Javascript 客户端表示已连接,但 Java 服务器没有

javascript - typescript 不会替换 tsconfig 中定义的非相对路径