Taming TypeScript

The TypeScript Tutorial for The Hater

The Myth of Verbosity: Your First 'Free' Types

Is TypeScript always verbose?

A common complaint about TypeScript is that it forces you to write extra code. But what if you could get all the safety benefits without writing any extra type annotations?

Most of the time, you can. TypeScript uses a feature called type inference to figure out the types of your variables automatically.

Your First "Free" Types with Inference

When you declare and initialize a variable, TypeScript "infers" its type from the value you assign.

Exercise 1: See the Inferred Types

  1. Hover your mouse over each of the variable names (playerName, score) in the code editor below.
  2. Notice the little popup that appears. TypeScript has automatically and correctly inferred their types as string and number.
Interactive Editor
Loading...

This is your first win. With zero extra syntax, you've prevented a whole class of bugs.

How to Explicitly Set a Type

Sometimes you want or need to tell TypeScript the type of a variable yourself. This is called a type annotation. The syntax is a colon : followed by the type.

let character: string;

Most of the time, if you're initializing the variable right away, this is redundant. let character: string = "Luigi" is not functionally different from let character = "Luigi". But knowing the syntax is crucial for the times you do need it.

Exercise 2: When is Annotation Necessary?

  1. Look at the status variable below. We declare it, but we don't assign it a value until later.
  2. Hover over status. Its type is any, a danger zone that means "anything goes."
  3. This allows us to assign a string, and then a number, with no errors. This is unsafe!
  4. Fix this by adding an explicit type annotation to the declaration. Change let status; to let status: string;.
  5. Now, the second assignment (status = 2) correctly shows an error.
Interactive Editor
Loading...

The rule is simple: If you declare a variable without initializing it, give it a type annotation. Otherwise, let TypeScript infer the type for you.

How const Creates More Specific Types (Literal Types)

Here's where TypeScript shows off how smart it is. When you use const, TypeScript knows the variable can never change. So it gets even more specific with the type.

Exercise 3: The const Difference

  1. Hover over charName below.
  2. Notice its type isn't just string. It's the literal value "Bowser"! This is called a literal type.
Interactive Editor
Loading...

This seems like a small detail, but it's a superpower. It allows TypeScript to be incredibly precise and enables powerful patterns we'll see in future lessons when we start combining these literal types.

For now, the key takeaway is:

  • let infers a general type (string, number).
  • const infers a specific, literal type ("Bowser", 100).
  • You only need to write type annotations when you aren't assigning a value right away.