TypeScript and React course Lesson 1 of 6

TypeScript from zero: a name has a type

A TypeScript name can carry a type. name is a string, cents is a number, and ready is a boolean. The program prints latte $4.50 ready.

Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.

Back to top

TypeScript adds types to JavaScript and checks them before the program runs. A cup label needs three. string is the drink. number is the price in cents. boolean is whether you can hand it over. You write the type after the name when you want it on the page. The value still has to match.

The annotation is checked, then erased#

TypeScript checks name, cents, and ready against the annotations and then erases them. The program that runs is JavaScript, and JavaScript does not consult : number. The value of the annotation is the errors you get while writing, including a call that passes a string where a number is required. cents = "450" fails in the checker. At runtime the three values are an ordinary string, number, and boolean, and console.log prints the label.

A cup label is three typed values
  1. namestringlatte
  2. centsnumber450
  3. readybooleantrue
const name: string = "latte";
const cents: number = 450;
const ready: boolean = true;
const status: string = ready ? "ready" : "sold out";
const frac = String(cents % 100).padStart(2, "0");
console.log(name + " $" + Math.floor(cents / 100) + "." + frac + " " + status);
latte $4.50 ready

The annotation is checked, then erased#

const cents: number = 450 stores 450 cents and tells the checker that cents is a number. That is $4.50. Math.floor(cents / 100) is the dollars. cents % 100 is the leftover cents, and padStart prints two digits. console.log prints the label. The running program is JavaScript. The types are gone by then. Their job was to refuse a bad assignment while you were editing.

cents = "450" does not compile, and const would also refuse a second assignment. let cents: number = 450 allows a later number and still refuses a string. Use const when the name should keep this value. Use the annotation when the value alone might be wider than you want, or when you are teaching the type, as this lesson is.

A parameter should say its type too#

function dollars(cents: number): number says the argument is a number and the return is a number. A caller who passes "450" is stopped. Leave the annotation off and the caller can pass anything, which is how a string ends up in a sum. The next lesson groups a string and a number in one object type.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.