Getting Started with TypeScript
Introduction to TypeScript and setting up your development environment
Getting Started with TypeScript
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
What is TypeScript?
TypeScript is a superset of JavaScript that adds static type definitions. It was developed by Microsoft and has gained widespread adoption in the JavaScript community.
Why Use TypeScript?
- Type Safety: Catch errors at compile time rather than runtime
- Better IDE Support: Enhanced autocomplete, refactoring, and navigation
- Self-Documenting Code: Types serve as inline documentation
- Easier Refactoring: Confident code changes with type checking
- Better Team Collaboration: Clear interfaces and contracts
Installation
You can install TypeScript globally or as a project dependency:
# Global installation
npm install -g typescript
# Project dependency
npm install --save-dev typescriptYour First TypeScript File
Create a file called hello.ts:
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet("World");
console.log(message);Compiling TypeScript
Compile your TypeScript file to JavaScript:
tsc hello.tsThis creates a hello.js file with the compiled JavaScript code.
TypeScript Configuration
Create a tsconfig.json file to configure the TypeScript compiler:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}Basic Types
TypeScript includes several basic types:
// Primitives
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
// Arrays
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
// Tuple
let x: [string, number] = ["hello", 10];
// Enum
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
// Any (avoid when possible)
let notSure: any = 4;
// Void
function warnUser(): void {
console.log("This is my warning message");
}Development Workflow
- Write TypeScript code with type annotations
- Use
tsc --watchfor automatic compilation - Run the compiled JavaScript with Node.js
- Use your IDE's TypeScript support for real-time error checking
Next Steps
In the following lessons, we'll dive deeper into:
- Interfaces and type aliases
- Classes and inheritance
- Generics
- Advanced types
- Working with external libraries
Let's continue building your TypeScript knowledge!