Compile arrow functions into regular functions with TypeScript

两盒软妹~` 提交于 2019-12-12 16:23:44

问题


Quite a simple question, but I haven't found an answer yet anywhere: Is there some switch to make TypeScript compile arrow functions into plain JavaScript functions?

I use them a lot in my code, and I don't want to rewrite everything. But I lately realized, that IE doesn't support them.

I already tried to switch the script version to ES5, but then my code won't compile anymore, because I'm using "filter" as well, which doesn't seem to be a part of it. However, I don't know, if that would do the job in the first place.


回答1:


If you want to just convert your arrow functions to regular functions and keep the rest of the code compiling, you can set the target config to es5 and lib property to es6:

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

This will allow your code that uses ES6 features to compile while targeting ES5. But you have to make sure those features (like filter) are available at runtime. If they are not available it will throw runtime exceptions.




回答2:


Arrow functions are a part of ES6, but you should be able to transpile your code to ES5 with Babel. There is a babel-preset-typescript which you should be able to use for this.



来源:https://stackoverflow.com/questions/46484830/compile-arrow-functions-into-regular-functions-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!