bhylu.com

Advertisements

TypeScript Functions

Function types describe parameters and the result. Use a small function to name a rule instead of repeating arithmetic wherever a button or request needs it.

How it works

A seed desk gives each visitor a fixed number of packets. The function below calculates the total from a visitor count and a per-person allowance. Its annotation makes the contract easy to inspect. A return type catches accidental changes such as returning formatted text from one branch. The caller still needs a rule for negative or fractional inputs; a numeric parameter does not supply that rule automatically.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

function packetTotal(visitors: number, allowance: number): number {
  if (!Number.isSafeInteger(visitors) || visitors < 0) throw new Error("Invalid visitors");
  return visitors * allowance;
}
console.log(packetTotal(4, 3));

Expected result

12

The guard rejects an invalid visitor count before multiplication. The valid fixture needs twelve packets. A complete application would also validate the allowance and impose a realistic upper bound. Keep those policies near the function that relies on them, rather than spread assumptions across its callers.