TypeScript Foundations·Types that pay for themselves

Types and inference

TypeScript checks JavaScript before it runs and infers most types for you.

Intermediate 12 min read Lesson 6 of 300 Challenge included
What you will be able to do
  • Primitive annotations: string, number, boolean, null and undefined.
  • let widens a value type; const keeps a literal type.
  • Enable strict mode so null and implicit any cannot slip through.

In plain English

An annotation is a promise about a value. Inference is the compiler filling in that promise when the answer is obvious. Good TypeScript uses inference for locals and explicit types at public boundaries.

inference.tsTypeScript
let title = 'TypeScript'      // inferred: string
const level = 'beginner'       // inferred: "beginner"

function label(name: string, score: number): string {
  return name + ': ' + score
}

// label('Ada', 'high') // Error: argument of type string is not number
Your turn

Type a score formatter

Easy

Write a function formatScore(name, score) that returns a string and rejects a string score at compile time.

TS · starter
function formatScore(name, score) {
  return name + ': ' + score
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What type does TypeScript infer for a const bound to the string "ready"?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 6 of 300 · 0% of course