typescript 打字稿 | Array.from | 错误 TS2339:类型“ArrayConstructor”上不存在属性“from”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36713651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript | Array.from | error TS2339: Property 'from' does not exist on type 'ArrayConstructor'
提问by Kania
I was googling, but cannot find the information what and how should I add to my project to allow me using ES6 methods like Array.from
我在谷歌上搜索,但找不到信息我应该添加什么以及如何添加到我的项目中以允许我使用 ES6 方法,例如 Array.from
__ EDIT: removed prototype word
__ 编辑:删除原型词
采纳答案by Nitzan Tomer
You can easily extend existing types like so:
您可以轻松地扩展现有类型,如下所示:
interface Array {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
The problem here is that this will add the function to the array instances and not as a static function like you require.
But that can be done like so:
这里的问题是,这会将函数添加到数组实例中,而不是像您需要的那样作为静态函数。
但这可以这样做:
interface ArrayConstructor {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
Then you should be able to use Array.from
.
那么你应该可以使用Array.from
.
Try it out on Playground.
在Playground上试一试。
Edit
编辑
If you need to polyfill the implementation (because the environment in which you intend to run doesn't have it), then this is how:
如果您需要对实现进行 polyfill(因为您打算运行的环境没有它),那么方法如下:
interface ArrayConstructor {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
Array.from = function(arrayLike: any, mapFn?, thisArg?): Array<any> {
// place code from MDN here
}
2nd edit
第二次编辑
Based on a comment, I'm adding a typed version:
根据评论,我添加了一个打字版本:
interface ArrayConstructor {
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
from<T>(arrayLike: ArrayLike<T>): Array<T>;
}
It's an exact copy of how it's defined in the lib.es6.d.ts.
它是lib.es6.d.ts 中定义的精确副本。
回答by mohamed hegazy
If you are sure the API exists on your engine at runtime, compile with --lib es6
(or --lib dom,es6
if you are using the DOM APIs).
如果您确定 API 在运行时存在于您的引擎上,请使用--lib es6
(或者--lib dom,es6
如果您正在使用 DOM API)进行编译。
See Compiler Options documentationfor more details.
有关更多详细信息,请参阅编译器选项文档。
回答by Vincent Buscarello
I hope it isnt terribly off topic but I found this while refactoring js to ts, and if you have an array like, it appears to work simply passing the array like to the constructor instead of using from, removing the need for the extra method.
我希望它不是非常离题,但我在将 js 重构为 ts 时发现了这一点,如果你有一个类似的数组,它似乎可以简单地将类似的数组传递给构造函数而不是使用 from,从而消除对额外方法的需要。
eg
例如
// someScript.js
Array.from( arrayLikeThing );
becomes
变成
// someScript.ts
Array( arrayLikeThing );
If there are other reasons to maintain using .from then the above answers are great.
如果还有其他原因需要继续使用 .from 那么上面的答案很好。