Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Very basic tsc usage#
I guess I have to learn TypeScript now.
Here’s how I got started in as few steps as possible, with the help of Get Started With Typescript in 2019 by Robert Cooper.
Installation using npm#
I created a new project:
1mkdir -p ~/Dropbox/Learning-TypeScript/first-typescript2cd ~/Dropbox/Learning-TypeScript/first-typescriptThen installed the TypeScript compiler:
1npm install --save-dev typescriptUsing --global instead of --save-dev would have installed in globally, but I’m not ready for that kind of commitment yet!
Apparently I need a tsconfig.json file. Running this command creates one for me containing some suggested defaults:
1% ./node_modules/.bin/tsc --initNext step: create a .ts file to start testing it out. I put the following in greetings.ts:
1const greeting = (person: string) => {2 console.log("Hello " + person);3};4
5greeting("Simon");Next, compile it! Thanks to npm install --save-dev typescript the tsc compiler is now available here:
1% ./node_modules/.bin/tscRun without any arguments it seeks out the tsconfig.json file, compiles any .ts files and produces matching .js files.
That seems to have worked:
1% node greetings.js2Good day Simon3% cat greetings.js4"use strict";5var greeting = function (person) {6 console.log("Good day " + person);7};8greeting("Simon");Running tsc —watch#
The --watch command continues to run and automatically compiles files when they are saved:
1% ./node_modules/.bin/tsc --watch2[9:32:44 AM] Starting compilation in watch mode...3
4[9:32:44 AM] Found 0 errors. Watching for file changes.I changed the last line of my greetings.ts file to greeting(1) (a type error) to see what happened:
1[9:33:56 AM] File change detected. Starting incremental compilation...2
3greetings.ts:5:10 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.4
55 greeting(1);6 ~7
8[9:33:56 AM] Found 1 error. Watching for file changes.Using npx#
Tip from @Benjie: you can use npx to avoid the ./node_modules/.bin prefix. I had thought that npx installed and ran a new global version, but it turns out it will notice your node_modules folder and run from that instead if one exists:
1% npx tsc --watchRunning this in Visual Studio Code#
VSCode has built-in TypeScript support. Hit Shift+Command+B and select the tsc: watch option and it runs that watch command in a embedded terminal pane inside the editor itself.