TypeScript: Unleashing the Power of Types on the Web!

How TypeScript Assists in Writing High-Quality Code

How TypeScript Helps You Write Better Code

Introducing TypeScript, the web’s new commander-in-chief! In this article, I’ll give you a high-level overview of the benefits of TypeScript and how it can help you create bug-free websites. Are you ready for a wild ride? Buckle up and let’s dive in!

What are Types? 🤔

In JavaScript, we have various data types like strings, numbers, arrays, objects, functions, booleans, undefined, and null values. These types determine the nature of our values and how we can interact with them. However, JavaScript is a dynamically typed language, which means variables can change types on the fly. It’s like a chameleon that can shape-shift whenever it feels like it:

let value = 'Hello';
value = 3;

On one hand, this flexibility is great, but on the other hand, it can lead to some serious foot-shooting if you’re not careful. JavaScript won’t warn you if you accidentally use the wrong type in your code. It’s like navigating a minefield without a map. Boom!

But fear not, my friends! TypeScript is here to save the day with static typing. With TypeScript, variables have fixed types and can’t change their stripes like a chameleon hopped up on caffeine. This enhances predictability and enables TypeScript to catch mistakes as you write your code, preventing them from exploding in your face later on. No more hidden bugs waiting to ruin your day!

You’re Already Using TypeScript! 😮

Hold on to your hats, folks, because here’s a mind-blowing revelation: you’re already using TypeScript, even if you’re writing plain old JavaScript! Let me explain. Imagine you’re using VS Code (the awesome code editor made by Microsoft) to write JavaScript code. When you hover over variables, VS Code magically reveals their types. It’s like a crystal ball that knows the secrets of your code:

function getGreeting(str) {
  return `Hello ${str}!`;
}

let input = 'Bob'; // Type: string
let greeting = getGreeting(input); // Type: string
let greetingLength = greeting.length; // Type: number

console.log(greeting, greetingLength);

Surprised? Don’t be! VS Code, in collaboration with TypeScript, analyzes your code and infers types based on context. It looks at your function and figures out that the return value must be a string. It’s like having a Type Detective working alongside you, solving the mystery of your code.

But wait, there’s more! TypeScript not only helps with variables but also checks the required arguments for built-in functions. For example, when you’re using the charAt or toUpperCase functions, VS Code shows you their proper signatures, as if opening the doors to the inner workings of JavaScript itself. You’ll never be left guessing again!

What About Edge Cases in JavaScript? 🤔

Ah, the dreaded edge cases, the sneaky little devils that love to break our code when we least expect it. These edge cases can drive us to the brink of madness, but fear no more! TypeScript is here to lend a helping hand.

In JavaScript, it’s easy to overlook edge cases and end up with frustrating bugs. For example, imagine a function that capitalizes a string. If you’re not careful, you might accidentally pass in the wrong type and receive a nasty surprise:

function capitalize(str) {
  if (typeof str !== 'string') return; // Oops! We forgot to handle this case
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

let input = 3;
let formattedInput = capitalize(input); // Type: string or undefined
let formattedLength = formattedInput.length; // Error!

JavaScript happily allows us to pass a number as an argument, and our function crashes and burns. Oops! TypeScript, however, will catch this mistake early on, preventing us from stepping on this banana peel. It’s like having a personal bodyguard who protects you from your own programming mishaps.

Turn the Code into TypeScript! 💥

Are you excited to unleash the full power of TypeScript? Let’s transform our code into a TypeScript beast! It’s as simple as changing the file extension from .js to .ts, and the magic begins.

Right away, TypeScript jumps into action and warns us that our formattedInput might be undefined. It’s like having a guardian angel watching over your code, pointing out potential pitfalls before they cause chaos:

function capitalize(str: string) {
  if (typeof str !== 'string') return; // No error here, TypeScript is vigilant!
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

let input = 'bob';
let formattedInput = capitalize(input);
let formattedLength = formattedInput.length; // Error caught by TypeScript!

By turning on strict mode in our TypeScript configuration, we can unleash even more power. TypeScript becomes more assertive, catching errors that could slip through the cracks. It ensures that our arguments are properly typed and forces us to handle edge cases. It’s like having an army of code guardians protecting your codebase!

Refactoring the Code: A Journey to Better Code 💪

Refactoring code can be daunting, but fear not! TypeScript comes to the rescue once again, guiding us through the treacherous path of refactoring.

Let’s say we decide to change our getGreeting function to accept an object with a first name and a last name, instead of two separate parameters. TypeScript allows us to precisely define the shape of objects, ensuring that we pass in the required properties:

type Person = {
  firstName: string,
  lastName: string,
  birthDay?: Date  // Optional property, because we want to keep things flexible
}

export function getGreeting(person: Person) {
  const formattedFirstName = capitalize(person.firstName);
  const formattedLastName = capitalize(person.lastName);
  return `Hello ${formattedFirstName} ${formattedLastName}!`;
}

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

As we make these changes, TypeScript immediately alerts us to any issues. It’s like having a loyal assistant double-checking your work, ensuring that you don’t miss a single piece of the puzzle:

let person: Person = {
  firstName: 'bob',
  lastName: 'dylan'
};

let greeting = getGreeting(person);
console.log(greeting);

Even better, TypeScript extends its watchful gaze beyond the current file. It highlights errors in nearby files, alerting you to any places that need adjustment. It’s like having a team of diligent inspectors, making sure your codebase remains clean and error-free.

TypeScript: Your Trusty Sidekick! 🦸‍♂️

To summarize, TypeScript is your mighty sidekick in the world of web development. It ensures that you wire together your application correctly, catches bugs before they cause chaos, and forces you to handle edge cases. TypeScript is like having an extra pair of eyes on your code, a loyal ally that prevents you from shooting yourself in the foot.

And remember, this is just the tip of the TypeScript iceberg. TypeScript has even more tricks up its sleeve, like advanced type inference, generics, decorators, and much more. So buckle up, explore the vast world of TypeScript, and unleash the full potential of your code!

💻Watch this article as a video if you prefer a more visual experience.

😄 Are you excited about the power of TypeScript? Share your thoughts in the comments below! And don’t forget to subscribe for more tutorials on web development and unleash your coding superpowers.

Stay tuned for the next adventure with TypeScript!

YouTube

Hunor Márton Borbély
Game development with JavaScript, creative coding tutorials, HTML canvas, SVG, Three.js, and some React and Vue
Follow me on Twitter
Check out my CodePen


Leave a Reply

Your email address will not be published. Required fields are marked *