Lesson 2 of 10

Type inference

Goal

Write a type only when you need one

01

Explanation

You don't need to write the type of every variable. From let total = 0 the compiler knows that total is a number, and from then on it won't let you assign a string to it. This is called type inference, and it covers most of your code.

Writing a type you don't need can even hurt: the line const cart: object = { items: 3 } throws away what the compiler knew about the object, so cart.items becomes a type error. Write a type where the compiler has nothing to infer it from, most importantly on function parameters.

Notice the difference between const and let. The type of const unit = "kg" is the literal type "kg", because its value will never change, while let unit = "kg" widens to string, because its value might.

02

Your task

Remove the explicit types that do harm, so that currency has the literal type "SAR" and the compiler knows cart.items is a number. Then give the parameter of toHalalas (a halala is a hundredth of a riyal) the type number so it rejects strings.

Checks

5 checks
  1. No type errors
  2. currency has the literal type "SAR"
  3. The compiler knows cart.items is a number
  4. toHalalas rejects a string
  5. toHalalas(42) returns 4200
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.