June 17, 2018 | Less than 1 minute to read
If you’re like me, most of your time writing bash scripts is spent Googling basic things like “how to loop in bash” while grumbling to yourself how easy this would be in a sane language like TypeScript.
As it turns out, you can write shell scripts using TypeScript, and it isn’t even that hard! Here’s how:
If you haven’t already, download and install node.
npm install typescript ts-node -g
Create a new
.ts file with a shebang as its first line that points to
Then, add some TypeScript-y stuff:
#!/usr/bin/env ts-node console.log('Hello from TypeScript!');
After saving your TypeScript file, you’ll need to update its permissions to allow it to be executed:
chmod u+x your-shell-script.ts
You can now run the script as you would any other command-line utility:
…which should result in a friendly message in your terminal:
> ./my-shell-script Hello from TypeScript!
That seemed a bit too easy - shouldn’t there be an intermediate build step in there somewhere? As a sanity check, update your
.ts file with something that shouldn’t compile:
#!/usr/bin/env ts-node console.log('Hello from TypeScript!'); // TypeScript compiler error: // Type '4' is not assignable to type 'string'. var myStr: string = 4;
Rerunning your script will now result in something like this:
/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:250 return new TSError(diagnosticText, diagnosticCodes) ^ TSError: ⨯ Unable to compile TypeScript: test.ts(5,5): error TS2322: Type '4' is not assignable to type 'string'. at createTSError (/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:250:12) at getOutput (/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:358:40) at Object.compile (/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:546:11) at Module.m._compile (/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:430:43) at Module._extensions..js (module.js:580:10) at Object.require.extensions.(anonymous function) [as .ts] (/Users/nathanfriend/.nvm/versions/node/v7.10.0/lib/node_modules/ts-node/src/index.ts:433:12) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Function.Module.runMain (module.js:605:10)
This is good! You shouldn’t be able to run a TypeScript file if it contains compile-time errors.
Other posts you may enjoy:
June 7, 2018 | 5 minutes to read
May 14, 2018 | 5 minutes to read
April 27, 2018 | 1 minute to read
June 26, 2017 | 6 minutes to read
January 26, 2015 | 6 minutes to read