Day 2: Your First Lines of TypeScript Code
Hey there,
Welcome back to Day 2 of the Daily TypeScript challenge! Yesterday, we answered the big "why" and got our tools ready. A huge congrats to everyone who shared their setup—it's awesome to see the community coming together.
Today, the theory stops. We're going to write some actual code.
Thinking in Types
The big shift from JavaScript to TypeScript is one simple idea: we tell our code what kind of data to expect ahead of time. Think of it like putting labels on your moving boxes. Instead of a generic "Box," you have "Kitchen Stuff," "Books," and "Important Documents." It makes everything easier to manage and far less likely that you'll open the wrong one.
In TypeScript, we start with three main "labels" or basic types:
Here’s how you use them. It’s just one extra little piece of syntax.
// We use a colon ":" after the variable name to declare its type.
let myName: string = "Alex";
let currentYear: number = 2025;
let isLearning: boolean = true;
That’s it! Now, if you try to assign the wrong type of data, TypeScript will immediately warn you.
But is TypeScript Smart? (Yes, it is)
You might be thinking, "Do I have to label everything?"
No, you don't. TypeScript is smart. If you declare and assign a variable on the same line, it can usually figure out the type on its own. This is called Type Inference.
let myCity = "Tirunelveli"; // TypeScript knows this is a string, no need for : string
let myAge = 25; // TypeScript knows this is a number.
Even without writing the type, your editor will still protect you from mistakes if you try to assign the wrong value later.
The Escape Hatch: any
What if you genuinely dont know what type a variable will be? TypeScript gives you an escape hatch: the any type.
let aWildVariable: any = "This could be a string...";
aWildVariable = 100; // ...or it could be a number. TypeScript won't complain.
Warning: Using any is like taking the labels off your boxes. You lose all the safety and autocomplete benefits of TypeScript for that variable. Use it very sparingly, usually when you're first migrating old JavaScript code.
Your Day 2 Challenge: Get Your Hands Dirty
It’s time to compile your first .ts file. This will show you how your TypeScript code turns into the plain JavaScript that browsers can run.
tsc day2.ts
You've officially written and compiled TypeScript!
That's a huge step. You've now experienced the core workflow.
Tomorrow, we'll level up and see how TypeScript handles the data structures you use every single day: arrays and objects.
See you then,
Manoj Prabhakar