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
- Hover your mouse over each of the variable names (
playerName
,score
) in the code editor below. - Notice the little popup that appears. TypeScript has automatically and correctly inferred their types as
string
andnumber
.
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?
- Look at the
status
variable below. We declare it, but we don't assign it a value until later. - Hover over
status
. Its type isany
, a danger zone that means "anything goes." - This allows us to assign a string, and then a number, with no errors. This is unsafe!
- Fix this by adding an explicit type annotation to the declaration. Change
let status;
tolet status: string;
. - Now, the second assignment (
status = 2
) correctly shows an error.
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
- Hover over
charName
below. - Notice its type isn't just
string
. It's the literal value"Bowser"
! This is called a literal type.
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.