TYPESCRIPT / CHAPTER 01
Read compiler feedback and run a checked program
IntermediateUse a type error as specific feedback while keeping type checking separate from execution.
By the end of this chapter
- Read a diagnostic at a function call
- Fix an argument instead of suppressing an error
- Distinguish checking from runtime output
The idea
TypeScript source must be checked and transformed into JavaScript before an ordinary JavaScript runtime can execute it. A TypeScript-aware editor or the TypeScript Playground can show both diagnostics and generated JavaScript. Enable strict checking for this course. With a local compiler, tsc --noEmit checks a project without writing JavaScript output.
Read the location and the two types in a diagnostic. If a function requires number but the call supplies "3", the caller supplied a string. Decide what the function actually accepts, then fix the caller or the contract. Removing an error message with any or a type assertion does not convert the runtime value. Start by making one small program check cleanly, then run it and compare its output with your prediction.
For the worked example, try changing the argument 3 to "3" in your editor. The checker should flag that call. Restore the numeric argument to make the contract and call agree. A clean type check is useful feedback, but a program can still compute the wrong formula; examples and tests check the intended behavior. This chapter assumes you can read a JavaScript variable and a simple function; links in the course introduction provide that preparation.
function triple(value: number): number {
return value * 3;
}
const result = triple(3);
console.log(result);9
The numeric argument matches the declared parameter type. After type annotations are removed, multiplication and printing follow normal JavaScript rules.
Try it yourself
In a TypeScript-aware editor with strict checking, change the call to triple("3") and read the error. Repair the argument, then test triple(0) and triple(-2).
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING