TYPESCRIPT / CHAPTER 02
Types as working contracts
BeginnerDescribe JavaScript values and function boundaries precisely.
By the end of this chapter
- Distinguish compile-time checking from runtime behavior
- Use inference for local values
- Annotate function inputs and results
The idea
TypeScript adds static checking to JavaScript; its type annotations are removed before ordinary JavaScript execution. The examples in this course assume strict checking. Start with string, number, and boolean, then describe array elements and function parameters. Let inference handle obvious local initializers, while explicit function boundaries communicate what callers may provide and what they receive.
A type is a contract the checker reasons about, not a runtime conversion or validator. Annotating a value as number does not turn text into a number, and a type assertion does not inspect downloaded data. Read an error as evidence that the implementation and its declared contract disagree. Correct the data flow or the contract instead of immediately silencing the diagnostic with any.
function lineTotal(price: number, quantity: number): number {
return price * quantity;
}
const total = lineTotal(7, 3);
console.log(total);21
The parameter annotations reject incorrectly typed calls during checking. Multiplication and console output still use normal JavaScript behavior after compilation.
Try it yourself
Define a typed function that formats a numeric quantity and a string unit into one string.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING