Lesson 2 of 10
Type inference
- 10 min
- 5 checks
- 3 hints
- Go to task
Goal
Write a type only when you need one
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.
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- No type errors
- currency has the literal type "SAR"
- The compiler knows cart.items is a number
- toHalalas rejects a string
- toHalalas(42) returns 4200