TypeScript Basics
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. It is a strict superset of JavaScript, meaning any valid JavaScript code is also valid TypeScript code. The key addition is static typing.
Why TypeScript?
- Catch Errors Early: Types allow you to catch bugs at compile time rather than runtime.
- Better Tooling: IDEs (like VS Code) provide excellent autocompletion, navigation, and refactoring support.
- Readability: Type definitions serve as documentation for your code.
1. Installation
You can install TypeScript globally or as a dependency in your project using npm (Node Package Manager).
Global Installation
npm install -g typescript
Verify the installation:
tsc --version
Local Installation (Recommended for Projects)
npm install typescript --save-dev
2. Basic Usage
Creating a TypeScript File
Create a file named hello.ts.
function greet(person: string, date: Date) {
console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
greet("Brendan", new Date());
Notice the type annotations (: string, : Date). If you try to pass a number to person, TypeScript will throw an error.
Compiling to JavaScript
Browsers and Node.js cannot execute TypeScript directly. You must compile (transpile) it to JavaScript using the TypeScript Compiler (tsc).
tsc hello.ts
This generates a hello.js file in the same directory, which you can run with Node.js or include in an HTML file.
node hello.js
3. Configuration (tsconfig.json)
For real projects, you don't want to run tsc filename.ts manually every time. You use a configuration file.
Initialize a configuration file:
tsc --init
This creates tsconfig.json. Common settings include:
{
"compilerOptions": {
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript. */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"strict": true, /* Enable all strict type-checking options. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. */
}
}
Now, you can simply run tsc in your terminal, and it will compile all files in src to dist based on these rules.
4. Basic Types
// Primitives
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
// Arrays
let list: number[] = [1, 2, 3];
let listGeneric: Array<number> = [1, 2, 3];
// Tuples (Fixed length array with known types)
let x: [string, number];
x = ["hello", 10];
// Enums
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
// Any (Opt-out of type checking)
let notSure: any = 4;
notSure = "maybe a string instead";
// Void (No return value)
function warnUser(): void {
console.log("This is my warning message");
}