Bitpath

Lesson 1 · Unit 01

Inference

What the compiler works out without being told

13 exercisesabout 3 min

What you practise

  • Annotations against inferred types, literal types and widening, let against const, any against unknown, strictNullChecks and 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?

TypeScript
let count = 5;
count = count + 1;
count = "six";

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.

TypeScript
let n = 5;             // number
let name = "Ada";      // string
function double(x: number) {
  return x * 2;        // returns number
}
const d = double(n);   // number

Concept

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.

TypeScript
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.

One email when Bitpath is ready to try. Nothing else. Privacy