bhylu.com

Advertisements

TypeScript Introduction

TypeScript checks JavaScript before you run it. A type describes which values a variable or function is allowed to receive; it does not turn external data into a trustworthy value.

How it works

A seed library records how many packets a visitor requests. JavaScript can add numbers and join text, so an accidental string could quietly change the result. A number annotation lets the checker reject that call while you are editing. The emitted JavaScript still performs ordinary JavaScript arithmetic. Start with one visible result, then distinguish a compiler complaint from an exception raised while the program runs.

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 remaining(stock: number, requested: number): number {
  return stock - requested;
}
console.log(remaining(18, 5));

Expected result

13

Both inputs are numbers and the return annotation promises a number. The checker verifies that relationship; the runtime calculates thirteen. Try changing the second argument to a quoted word in your local project and read the compiler message. That check does not prove a request is positive or below the available stock; those are separate business rules.