可以使用Babel转换成TypeScript吗?

我了解到Babel now has support for TypeScript的样式类型注释。但是,它不会像TypeScript编译器那样检查类型,并且会从输出中删除类型注释。我想实现的是:

  1. 将带有TypeScript注释的Stage-0代码转换为原始TypeScript
  2. 使用TypeScript编译器检查类型
  3. 输出与Node或浏览器兼容的JavaScript

这可能吗?

ioublack 回答:可以使用Babel转换成TypeScript吗?

我很好奇,所以我pinged Nicolò Ribaudo在Babel上做了很多工作,事实证明这比我想象的要容易:您可以告诉Babel进行 parse 类型注释,但不能使用TypeScript 语法插件MyGenericClass<int>删除,但不使用TypeScript preset @babel/plugin-syntax-typescript)删除它们。

例如,如果您想转换对管道运算符的支持,您的@babel/preset-typescript可能看起来像这样:

.babelrc

然后,如果您将这个{ "plugins": [ "@babel/plugin-syntax-typescript",[ "@babel/plugin-proposal-pipeline-operator",{ "proposal": "minimal" } ] ] } 文件喂给Babel:

.ts

...它会在管道运算符被转译的情况下生成此输出,但是类型注释仍然存在:

function doubleSay(str: string) {
  return str + "," + str;
}
function capitalize(str: string) {
  return str[0].toUpperCase() + str.substring(1);
}
function exclaim(str: string) {
  return str + '!';
}

let result = "hello"
  |> doubleSay
  |> capitalize
  |> exclaim;

console.log(result);
本文链接:https://www.f2er.com/3160462.html

大家都在问