Welcome to the Wild World of TypeScript, Mate! Is it scary?

So, what’s this TypeScript thing anyway?! 🫣

Greetings to friends, colleagues, internet denizens — even those of you who arrived here by sheer mistake of the algorithm — you are all very welcome.

Alright, you wanna get your hands dirty with TypeScript, huh? Well, buckle up, because this ain’t your mama’s JavaScript tutorial. Let’s straight to the point!

Let’s cut the formalities, TypeScript is just JavaScript with some mad skills. It’s like JS went to the gym, trained hard, and came back all beefed up.

This superscript of JavaScript brings static types, interfaces, and classes right into the mix. Why, you ask? Well, these features help you write more maintainable code, plus it makes it a lot easier to work on large projects.

I. «Rolling up the Sleeves: Beginner’s Examples»

When we say JavaScript, it conjures up visions of a playful, untrained puppy — very lovable, but oh boy, it can make a mess if you’re not careful. Dynamically typed, it will let you do things you probably shouldn’t, like assigning a string to a variable that was initially an integer. It’s fun, it’s unpredictable, it’s…a debugging nightmare.

let count = 1;
count = 'one'; // JavaScript says, "Sure, why not?"

Now picture a more disciplined sibling stepping into this whirlwind. Meet TypeScriptJavaScript’s sophisticated cousin who believes in rules and manners. It’s like someone finally taught our puppy to sit, roll over, and definitely stop chewing the slippers.

let count: number = 1;
count = 'one'; // TypeScript yells, "Hold up! You can’t do that!"

Alright, let’s get down to the nitty-gritty. Say you’re writing a function in JavaScript that multiplies two numbers. Here’s how you might do it:

function multiply(a, b) {
return a * b;
}

Using JavaScript, you could pass anything to this function — a string, a boolean, heck even an object if you’re feeling particularly adventurous.
But with TypeScript, we can tell our function exactly what we expect:

function multiply(a: number, b: number): number {
return a * b;
}

See those little : number parts? That's TypeScript telling our function that it better be getting numbers, or else there's gonna be trouble. But fear not, this trouble is good trouble; it saves us from making silly mistakes in our code. Plus, it gives your IDE superpowers to help you while coding.

Incorporating TS into your projects is like forcing your uncontrolled, free-spirited JavaScript to ‘adult’. Variables are no longer a free-for-all. Now they have responsibilities and commitments, and they stick to them.

let canWeAssignAnything: string = 'Nah, mate!';
canWeAssignAnything = 404; // TS says: I’m afraid, I can’t let you do that!

In general, imagine JavaScript — that unruly, spontaneous trickster, a jester in the court of programming languages. Now, visualize a version of JavaScript that’s more refined, slightly more predictable, and takes fewer liberties with your code. That’s TypeScript — the courtier with the courteous manners and a knack for playing by the rules.

Now let’s Dive Deep: TypeScript Interfaces

Let’s say you’re creating objects that represent users in your system.
In JavaScript, you just make an object and hope for the best result.

let user = {
name: 'Johnny',
age: 21
};

But with TypeScript, we can describe exactly what a user should look like using an interface. Btw, you can use this interface to type check objects.

interface User {
name: string;
age: number;
active: boolean;
}

let user: User = {
name: 32, // TypeScript, being a good friend, lets you know you messed up.
age: 'Ace Ventura', // Type 'string' is not assignable to type 'number'.
active: true
};

Now, TypeScript will yell at you

…if you try to make a user that doesn’t fit this mold. Cool, huh?
So we’re ready to go into the wild world! Let’s see the magic!

let hello: string = "Hello,";
let world: string = "World!";

world = "Bleverse!";

console.log(hello+" "+world);

Using TypeScript isn’t just for making your code more structured and predictable. It’s also like having a secret weapon that offers auto-completion, static checking, and a form of documentation. It’s like that handy multi-tool you carry around — you never know when you’ll need it, but when you do, you’re really glad it’s there.

Setting Up a TypeScript Project

TypeScript can’t be understood by browsers, so it has to be compiled into JavaScript by the TypeScript Compiler (TSC). First, install Node.js LTS, and now you should have PNPM installed. Just run pnpm add -g typescript now.

Your Beginner TypeScript To-Do List:

  1. Install Node.js and TypeScript. I also recommend installing VS Code.
  2. Create a folder for your project. Run the tsc --init command there.
  3. Create .ts file and write some code. Use the examples above as a guide.
  4. Compile: tsc yourFileName.ts creates a JS file with the same name.
  5. Run node yourFileName.js command to see your script in action!

II. «TypeScript’s Wit & Charm: Everyday Types»

Alright, champ, you seem to have a thirst for knowledge, and I love it! Let’s take a closer look at TS’s types and see what they’ve got for us. It’s really exciting!

Basic Everyday Types in TypeScript (1)

Just like in JavaScript, we’ve got our basic types. We have:

  • boolean: true or false.
  • number: All numbers, including float, integer, and so on. There’s no distinction between different types of numbers.
  • string: Text, mate, just text.

Here’s how we use them:

let isDone: boolean = false;
let decimal: number = 2023;
let color: string = "blue";

Beyond the Basics of TypeScript Types

Now, let’s move past the kiddie pool and jump into the deep end.
TypeScript offers some powerful type tools that’ll rock your socks off.

Arrays. This one is straightforward. An array of a type is denoted by type[] or Array<type>. Just check this very basic example:

let list: number[] = [1, 2, 3];
let anotherList: Array<number> = [1, 2, 3];

Tuple. Think of tuples as arrays where the type of fixed number of elements is known, but doesn’t have to be the same.
Here’s how you’d declare a tuple:

let x: [string, number];
x = ["hello", 10]; // That's alright
x = [10, "hello"]; // Nope, TypeScript won't let this happen.

Enums. They allow us to define a set of named constants. This makes it easier to document intent or create a set of distinct cases. Example:

enum Color {
Red,
Green,
Blue
}

let c: Color = Color.Green;

Any. We use any when we're not sure what type our variable might be. It's a powerful way to opt out of type-checking if we expect the type to change or if it's too complex to map.

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

Void. It is like the any opposite: the absence of having any type at all. We mostly use void as the return type of functions that don't return a value.

function warnUser(): void {
console.log("This is my warning message");
}

Null and Undefined. Just like in JavaScript, undefined and null are valid values. By default, they're subtypes of all other types, meaning you can assign null and undefined to something like number. When you turn on a certain flag (--strictNullChecks), they get their own separate types, and you can't assign them to anything else (unless you explicitly state so).

let u: undefined = undefined;
let n: null = null;

TypeScript Types To-Do List:

  1. Play with the types: Try creating variables of different types and see how TypeScript handles them.
  2. Experiment with arrays and tuples: Can you create an array of tuples? Or, say, a tuple of arrays?
  3. Define your own enum: Try making an enum for something.
  4. Try out any and void: See how TypeScript treats these special types.
  5. Toggle the --strictNullChecks flag: See how null and undefined behave differently.

Now you know your way around TypeScript types! Remember, friend, this is your toolbox. It’s up to you to decide when and where to use each tool.

Application of TypeScript Knowledge

Now, where can you use this TypeScript stuff? Just about everywhere!

  1. Web Applications: TypeScript works beautifully with front-end frameworks like React (❤️ Next.js️), Angular, Vue, and others.
  2. Node.js Applications: Writing your back-end code in TypeScript helps catch bugs before they creep into your system.
  3. Game Development: TypeScript is also used in game development with libraries like Phaser.
  4. Mobile Apps: With frameworks like Ionic and React Native, TypeScript shines in the mobile realm too.

III. «The Bug is Dark and Full of Errors»

But fear not! Remember, dear friends, for TypeScript is here to light your way.

So, what’s the panacea for the idiosyncrasies of TypeScript? The answer is as simple as it is effective — embrace them. TypeScript has many virtues to its name, one of which is its talent for catching errors early.

In the chaotic mosh pit of JavaScript coding, it’s easy for bugs to slip past unnoticed, until one day they decide to make a grand appearance, just when you least want them. TypeScript, on the other hand, loves to play spoilsport to such melodramatic revelations.

TypeScript: The Strict Mentor We All Need

It points out your follies before they can come back and haunt you, like a friendly ghost that tidies up instead of creating a mess. But despite its many virtues, TypeScript isn’t without its quirks. It’s slightly pedantic, a stickler for rules, and at times, more rigid than a maiden aunt. The very trait that makes TypeScript a lifesaver can also make it a tad annoying. It insists on types, just as a pompous professor might insist on complete sentences.

Have a function that’s happy to receive any kind of input? Not on TypeScript’s watch! It demands you declare the type upfront, like a bouncer at an exclusive club. And just like that bouncer, if you mess up the type, you’re not getting past the door. This strictness can be exasperating, especially when you’re knee-deep in coding and TypeScript refuses to budge until you’ve dotted all your i’s and crossed your t’s.

But for all its seeming inflexibility, it is a blessing in disguise. It forces you to think, to plan, and to code more deliberately. It’s like that grumpy but wise mentor who is hard on you, but only because they want you to be the best you can be. Learn to cherish TypeScript’s quirks, much as you’d enjoy the quirks of a particularly colorful character at a party.

The Party Begins! With TypeScript!

It’s the oddities that make it interesting, and the sternness that makes it indispensable. Learn its rules, respect its discipline, and you’ll find that TypeScript isn’t the party pooper it seems to be. Instead, it’s the life of the coding party, keeping things running smoothly and ensuring that no bugs gatecrash your painstakingly crafted code.

It’s time for a call to action, dear reader. Arm yourself with the shield of discipline, the sword of knowledge, and join the TypeScript battalion. Don’t be the code scribe that lets bugs roam free, be the one that keeps them at bay with well-typed code. If you’re already coding in JavaScript, take the leap to TypeScript. If you’re a novice just starting out, why not start with the best?

IV. «So, Have We Reached the Bottom Line?»

Dear friend, we are still at the very beginning, a long journey still awaits you…

Alright, I just gave you the keys to the kingdom, but don’t go rushing in just yet. There are many other cool features in TypeScript like classes, generics, decorators, etc. We’ll touch them in the future. Don’t be afraid to explore!

So, let’s pop the cork and raise our glasses to TypeScript. Sure, it may feel like the party pooper when it doesn’t let you casually mix types or access non-existent properties. But, if you ask me, it’s the responsible friend who ensures you don’t text your ex at 2 AM after a night out. In the end, it saves you a lot of headaches and regret. Cheers, my friends and dear readers!

So here’s to TypeScript, the well-behaved sibling who keeps us out of trouble.

It may feel like a stick in the mud at times, but it’s got our backs, helping us create cleaner, safer, and more reliable code. Here’s hoping your journey with TS is filled with wit, clarity, and significantly fewer runtime errors.

So, mate, that’s a bit of TypeScript for ya. Feeling adventurous? What kind of project are you planning to use TypeScript on? What other TypeScript topics do you want to explore? Let me know in the comments section!

And, yeah! This is my first publication. So please don’t judge me too harshly 😅

References & Future Reading

[1] Everyday Types. TypeScript Documentation, Jun 2023.

Feel free to drop a message on LinkedIn/Email for feedback and suggestions.

--

--

Nazar Kornienko Blefnk, Relivator, Bleverse
Nazar Kornienko Blefnk, Relivator, Bleverse

Written by Nazar Kornienko Blefnk, Relivator, Bleverse

Frontend Developer ▲ Next.js, React, JavaScript, TypeScript, WordPress, Html, Css. Inclusive UX/UI designer. Open to freelance project and full/remote work.

No responses yet