【问题标题】:es6 features not compiling in TypeScriptes6 功能未在 TypeScript 中编译
【发布时间】:2018-12-22 21:50:47
【问题描述】:

我是 TypeScript 新手,在编译 es6 代码时遇到了一些问题。

我有一个 .ts 文件:

let a: number[] = [1,34,5,5,34,3];

console.log(a.find(no => no == 5));

当我运行tsc --module es6 --target es2015 src/test.ts 时,它编译得很好,但是tsc --module es6 --target es5 src/test.ts 似乎不起作用?我想以 es5 为目标,但这样做会给我错误:

Property 'find' does not exist on type 'number[]'.

TypeScript 不能编译成 es5,还是需要在 TypeScript 编译器上运行 babel?

【问题讨论】:

  • 你不能把它编译成 es5。因为es5中没有find,而且typescript不会编译target中不存在的函数,而是编译语法。
  • @HikmatGurbanli 是的,你可以只需要指定库 :)
  • @TitianCernicova-Dragomir 我不知道解决方案,但知道问题所在。谢谢你的启发

标签: javascript typescript


【解决方案1】:

Typescript 可以编译成 es5,唯一的问题是 find 方法是在 es2015 标准中定义的,所以 typescript 会假设它不存在。

Typescript 有两种方法可以控制您编译到的标准target 告诉编译器如何编译语法,lib 告诉编译器运行时环境是什么样的(请参阅here 以获得更详细的答案例子)

要以es5 为目标,但要获得find 方法,您还需要指定库:

tsc --module es6 --target es5 src/test.ts --lib es2015,dom,scripthost

请注意,typescript 不会提供任何 polyfill,您可以自带或希望 find 存在于运行时中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 2020-04-28
    • 1970-01-01
    • 2016-09-23
    • 2016-05-25
    • 1970-01-01
    • 2016-09-12
    • 2015-10-23
    相关资源
    最近更新 更多