Part 1: Getting Started with TypeScript
Unlock the power of a strongly-typed superset to write safer, scalable, and more maintainable JavaScript.
Why TypeScript?
Let’s face it: JavaScript is flexible—almost too flexible. While this makes it fun to work with, it also opens the door to sneaky runtime errors that can cause your application to break unexpectedly.
Here’s where TypeScript, a superset of JavaScript, swoops in to save the day. It introduces static typing, making your code easier to debug, scale, and maintain. Think of TypeScript as your project’s safety net.
Key Benefits:
- Early Error Detection: Catch bugs during development, not runtime.
- Code Readability: Helps teammates understand your code better.
- Scalability: Makes working on large codebases a breeze.
Getting Your Environment Ready
To write and run TypeScript, we need a few tools. Don’t worry—it’s as simple as brewing your morning coffee.
1. Install Node.js and npm
Download and install the latest Node.js version. npm (Node Package Manager) comes bundled with Node.js.
Verify installation:
node -v
npm -v
2. Install TypeScript Compiler
Open your terminal and run:
npm install -g typescript
Verify installation:
tsc -v
3. Set Up a New Project
Create a project folder and navigate into it:
mkdir my-typescript-project
cd my-typescript-project
4. Initialize the Project
Generate a tsconfig.json
file, which configures your TypeScript compiler:
tsc --init
This creates a default config file. You can tweak it as your project grows.
Your First TypeScript Program
Let’s write a simple program that adds two numbers.
Create a file named index.ts
:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 10)); // Output: 15
Compile the file:
tsc index.ts
This generates a JavaScript file (index.js
).
Run the compiled file:
node index.js
Congratulations, you’ve just written and executed your first TypeScript code! 🎉
What Just Happened?
- The
: number
annotation ensures the parametersa
andb
are numbers and that the function returns a number. - If you pass anything other than numbers to
add()
, TypeScript will throw a compile-time error.
Try this:
console.log(add("5", 10));
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
This is TypeScript in action—catching bugs before they happen!
How TypeScript Works
- Type Checking: TypeScript analyzes your code for potential type mismatches.
- Compilation: TypeScript converts your .ts files into browser-ready .js files.
Next Steps
You’ve scratched the surface of TypeScript. In the next part, we’ll dive into Type Annotations, where you’ll learn to describe your variables, functions, and data structures with types.
Top comments (0)