Setting Up TypeScript
In this page:
Checking Node.js and npm
Node.js includes a runtime for JavaScript and provides npm, which is commonly used to install TypeScript and other development tools. Checking the installed versions helps confirm that the environment is ready.
Example: Checking Node.js and npm
// Run in a terminal (not executable here):
// node -v
// npm -v
console.log("Check installed versions with: node -v && npm -v");
Installing TypeScript
TypeScript can be installed as a project development dependency with npm. Installing it locally keeps the compiler version associated with the project and allows npm scripts or npx to use that version.
Example: Installing TypeScript
// Run in a terminal (not executable here):
// npm install typescript --save-dev
console.log("Installed as a project dev dependency via npm");
Creating a TypeScript File
TypeScript source files normally use the .ts extension. You can create a file such as app.ts and place typed TypeScript code inside it.
Example: Creating a TypeScript File
// app.ts
let projectName: string = "My First App";
console.log(projectName);
Running the Compiler
The TypeScript compiler is commonly invoked with the tsc command. Given a TypeScript file, the compiler checks the code and can generate a JavaScript file that can then be executed by a JavaScript runtime.
Example: Running the Compiler
// Run in a terminal (not executable here):
// tsc app.ts
let result: string = "app.ts compiled to app.js";
console.log(result);
Verifying the Setup
After installing TypeScript, you can verify that the compiler is available by checking its version. A successful version output indicates that the TypeScript compiler can be accessed from your environment.
Example: Verifying the Setup
// Run in a terminal (not executable here):
// tsc --version
console.log("A version number confirms tsc is accessible");
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: