I understand that Babel now has support for TypeScript style type-annotations. However, it does not check the types like the TypeScript compiler does, and it removes the type annotations from the output. What I would like to achieve is:
Is this possible?
I was curious so I pinged Nicolò Ribaudo who does a lot of work on Babel, and it turns out this is easier than I thought: You can tell Babel to parse type annotations but not remove them by using the TypeScript syntax plugin ( @babel/plugin-syntax-typescript
) but not the TypeScript preset ( @babel/preset-typescript
).
For instance, if you wanted to transpile support for the pipeline operator, your .babelrc
might look like this:
{
"plugins": [
"@babel/plugin-syntax-typescript",
[
"@babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
]
]
}
Then if you feed Babel this .ts
file:
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);
...it generates this output with the pipeline operator transpiled but the type annotations still in place:
var _ref, _ref2, _hello;
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 = (_ref = (_ref2 = (_hello = "hello", doubleSay(_hello)), capitalize(_ref2)), exclaim(_ref));
console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.