Type information describes the types associated with program values and expressions at compile time. It lets the TypeScript compiler check JavaScript usage before execution instead of allowing unsafe calls to reach runtime. section 15.3 section 7.2.2
Type information can enter a project in several ways:
- Infer types from initialized values and expressions, such as number[] for prices and string[] for names. section 9.2.1
- Add TypeScript annotations directly, such as amount: number or a function return type. section 7.2.2
- Describe JavaScript with JSDoc comments, including unions such as number | string. section 15.3.1
Preventing an unsafe formatter call
A JavaScript formatter that calls cost.toFixed(2) can fail when passed a string. JSDoc supplies the missing contract: /** * @param {string} thing * @param {number} cost */ export function costFormatter(thing, cost) { writeMessage(`The ${thing} costs $${cost.toFixed(2)}`, true); } The compiler then rejects costFormatter("Cart", `${cart.totalPrice}`) instead of waiting for the runtime TypeError. If both forms are valid, declare cost as number | string and narrow it with typeof before calling toFixed. section 15.3 section 15.3.1
Inspecting inferred results
Changing calculateTax to return (amount * 1.2).toFixed(2) changes taxAmount from number to string. The later expression taxAmount / 2 therefore produces a compiler error. Enabling declaration in tsconfig.json emits index.d.ts, which reveals declarations such as: declare let prices: number[]; declare let names: string[]; declare let taxAmount: string; dist contains generated output; edit the TypeScript source rather than the emitted JavaScript. section 7.2.2 section 9.2.1 section 5.5
Listing 15.16 Using JSDoc in the formatters.js file in the src folder
// @ts-nocheck
export function sizeFormatter(thing, count) {
writeMessage(`The ${thing} has ${count} items`);
}
/**
* Format something that has a money value
* @param { string } thing - the name of the item
* @param { number} cost - the value associated with the item
*/
export function costFormatter(thing, cost) {
writeMessage(`The ${thing} costs $${cost.toFixed(2)}`, true);
}
function writeMessage(message) {
console.log(message);
}
Inspect the complete JSDoc formatter listing, including parameter types and the JavaScript implementation. section 15.3.1

