Types and inference
TypeScript checks JavaScript before it runs and infers most types for you.
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.
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 numberYour turn
EasyType a score formatter
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.