Lesson 1 · Unit 01
Inference
What the compiler works out without being told
What you practise
- Annotations against inferred types, literal types and widening,
letagainstconst,anyagainstunknown,strictNullChecksand the missing value
Try a question from this lesson
Pick one
There is no annotation anywhere. Python would run all three lines and happily rebind the name. Which line does the TypeScript compiler reject?
let count = 5;
count = count + 1;
count = "six";Correct answer
Line 3
Why
The compiler inferred number from the first value, and that is the type of count for good. Line 3 is rejected before the program ever runs. In Python a name can point at anything; here the variable itself has a type.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Inference
You rarely write types for variables. The compiler reads them off the values, and the type of a function's result off its return.
Parameters are the exception: nothing inside the function says what callers will pass, so you annotate them. Think of Python type hints, except that they are enforced and mostly filled in for you.
let n = 5; // number
let name = "Ada"; // string
function double(x: number) {
return x * 2; // returns number
}
const d = double(n); // numberConcept
any and unknown
Both accept every value. They differ in what you may do next.
any turns the checker off: any property, any call, no questions. unknown means "could be anything, so prove it first": nothing is allowed until a check narrows it.
Reach for unknown. any is a hole in the net.
let a: any = "hi";
a.toFixed(2); // compiles, crashes
let u: unknown = "hi";
// u.toFixed(2); // rejected
if (typeof u === "string") {
u.toUpperCase(); // a string in here
}10 more exercises in the app
- 1× true or false
- 4× multiple choice
- 2× fill the blanks
- 2× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.