Thuta Learning
TypeScript
BasicProgrammingIntermediate

What is TypeScript?

TypeScriptLesson 220 min

What you'll walk away with

  • Explain the difference between dynamic typing (JavaScript) and static type checking (TypeScript) with an example
  • Separate what is true and what is not in the claim 'all JavaScript is valid TypeScript'
  • Predict the type TypeScript infers for a variable that has no annotation
  • Write out the JavaScript that remains once the types are erased from a `.ts` file

Explain it simply

What TypeScript is, simply

TypeScript is an open-source programming language created by Microsoft. It is called a superset of JavaScript: it keeps everything JavaScript has and adds types on top. Classes, arrow functions, async/await and the rest of the syntax all come from JavaScript; what TypeScript adds is static types and syntax for describing types, such as interfaces.

Browsers never run TypeScript directly. The compiler checks the types, removes them, and hands you plain JavaScript. So you can think of TypeScript as a layer that helps you while you write, and then steps out of the way.

Problem → Why → Solution

The problem: JavaScript cannot see a typo

JavaScript is dynamically typed. It only learns what type a value has, or which properties an object has, while the code is running. In the code below, `firstName` was typed as `firstname` (lowercase n).

To JavaScript, reading a property that does not exist is not an error; it simply returns `undefined`. So 'Welcome, undefined' goes straight to the user, and nobody notices unless a test checks that exact sentence.

greet.js
const user = { firstName: "Su", lastName: "Mon" };

// One wrong letter: firstname instead of firstName
console.log("Welcome, " + user.firstname); // Welcome, undefined

Why TypeScript can catch it

TypeScript looks at the `user` object and knows it has only `firstName` and `lastName`. Put this code in a `.ts` file and you get 'Property firstname does not exist ... Did you mean firstName?' before it ever runs. You did not write a single annotation; inference did the work.

Core concept: superset, static checking, erasure

'Superset' is true at the level of syntax: the TypeScript compiler can parse every valid JavaScript program and emit JavaScript from it. But 'all JavaScript is error-free TypeScript' is false. `let n = 5; n = "five";` is perfectly fine JavaScript, yet TypeScript reports an error because it inferred `n` to be a number. That is not a flaw; it is the reason TypeScript exists.

AspectJavaScriptTypeScript
When types are knownWhile running (run time)Before running (compile time)
A type mistake causesA wrong result or a crashAn error in the editor or tsc
What actually runs.js directly.ts turned into .js first

'Static' here means the check reads the source code without running it. The compiler reads every file, follows each value from where it is created to where it is used, and reports every place where a promise could be broken, including branches your tests never reach. A test proves that one path works; a type check covers all paths at once.

It only answers questions types can answer, though ('is this a number?'), not business rules ('is this price correct?'). That is why TypeScript complements tests rather than replacing them. TypeScript has been public since 2012 and is still developed in the open on GitHub.

You do not write every type yourself. Write `let count = 0` and TypeScript infers that `count` is a number. Annotations go mainly where inference has nothing to work from, such as function parameters.

The last idea is type erasure. During compilation every `: string`, `: number` and interface is removed, while the logic stays exactly the same. At run time `typeof` only sees JavaScript's own types ("string", "number"); the names of your interfaces no longer exist.

Two layers of a TypeScript file
  1. Value layer: the JS that runs
  2. Type layer: : string, interfaces
  3. Compiler checks the layers match
  4. Type layer erased, values run

The type layer never changes what the program does at run time; it only checks it.

General pattern: annotation vs inference

typescript
let explicitName: Type = value;   // you state the type
let inferredName = value;          // TypeScript works it out

function name(param: Type): ReturnType {
  // parameters need annotations; return type can be inferred
}

Variables that start with a value rarely need an annotation. Parameters do, because nothing tells the compiler what value will be passed in.

TypeScript code and the JavaScript it becomes

This example has two annotated variables and one function. The last log line shows what `typeof` sees at run time, and the comments at the bottom show the JavaScript that is left once the types are erased.

intro.ts
// TypeScript: annotations say what each value must be
let message: string = "Hello, TypeScript";
let firstReleased: number = 2012;

function describe(language: string, year: number): string {
  return `${language} has been public since ${year}`;
}

console.log(message);
console.log(describe("TypeScript", firstReleased));
console.log(typeof message, typeof firstReleased);

// What tsc emits - the same code with the types removed:
//   let message = "Hello, TypeScript";
//   function describe(language, year) { return `...`; }

Code breakdown

  1. An annotated variablelet message: string = "Hello, TypeScript";

    A promise that `message` only ever holds a string. Writing `message = 42` later would be a compile error.

  2. A typed function signaturefunction describe(language: string, year: number): string {

    Both parameters are annotated, so the compiler catches a swapped call such as `describe(2012, "TypeScript")`.

  3. Runtime only sees JavaScript typesconsole.log(typeof message, typeof firstReleased);

    Prints `string number`. These are JavaScript's own `typeof` results; the TypeScript annotations cannot be read at run time.

  4. The emitted JavaScript// let message = "Hello, TypeScript";

    After compilation `: string` is gone and ordinary JavaScript remains. The types changed nothing about the program's logic.

You should see
Hello, TypeScript
TypeScript has been public since 2012
string number

How TypeScript code actually gets run

Type checking and producing JavaScript (emitting) are two separate jobs. `tsc` can do both. Bundlers such as Vite, runners such as `tsx`, and runtimes such as Deno and Bun strip the types quickly and run the code, but they do not type-check it. Recent Node.js versions can also strip types from simple `.ts` files (check the Node.js docs for the details). That is why most projects run `tsc --noEmit` separately just for type checking.

In real projects

How teams adopt TypeScript in practice

Because TypeScript is a superset, an existing JavaScript project does not need a big-bang rewrite. Most teams rename one `.js` file to `.ts`, fix the errors that appear, then move on to the next file. With the `allowJs` option, `.js` and `.ts` files can live side by side in the same project.

The first bugs such a migration finds look like the ones in this lesson: a misspelled property name, a value that might be `undefined` but is never checked, a function called with the wrong number of arguments. VS Code also analyzes plain `.js` files with the TypeScript engine, so even while you write JavaScript, much of your autocomplete is coming from TypeScript.

Common mistakes

Common misunderstandings

"It's a superset, so my JS will just compile cleanly"

Renaming `.js` to `.ts` often produces a pile of errors. Most come from a variable holding several types (`let id = 1; id = "A1"`) or an object that starts as `{}` and gets properties added later. TypeScript is not broken; it is showing problems that were already hiding there.

Expecting to inspect types at run time

Code like `typeof value === "User"` never works. The `User` interface is gone after compilation and `typeof` only answers "object". To tell values apart at run time you check a property instead, which the Type Narrowing lesson covers in detail.

Assuming the bundler type-checks for you

With `tsx` or Vite, a program with type errors still runs. Add `tsc --noEmit` to your CI so the errors cannot slip through.

Best practices

Habits worth building from the start

  • Skip annotations where inference already works; write them on parameters and on the return types of exported functions
  • Read an error message from its first line and look for the expected type and the type that was received
  • Hover over variables in your editor often to see which type TypeScript actually inferred

Mini challenge

Mini challenge: convert JavaScript to TypeScript

Write two fully annotated functions: one converts Celsius to Fahrenheit, the other describes a city's temperature using it.

  • `toFahrenheit` takes a number and returns a number (`C * 9 / 5 + 32`)
  • `describeTemperature` takes a city (string) and celsius (number) and returns a string
  • Print the result for Yangon at 30°C and Mandalay at 35.5°C
  • Explain why the compiler rejects `describeTemperature(30, "Yangon")`
temperature.ts
// TODO: annotate the parameter and the return type
function toFahrenheit(celsius) {
  // TODO: convert with C * 9 / 5 + 32
}

// TODO: city is a string, celsius is a number, the result is a string
function describeTemperature(city, celsius) {
  // TODO: return "<city>: <C>°C is <F>°F" using toFahrenheit
}

// TODO: print Yangon (30) and Mandalay (35.5)

Expected: Prints `Yangon: 30°C is 86°F` and `Mandalay: 35.5°C is 95.9°F`.

Show hint

Writing the return type also makes the compiler catch a forgotten `return` inside the function.

Show solution
temperature.ts
function toFahrenheit(celsius: number): number {
  return (celsius * 9) / 5 + 32;
}

function describeTemperature(city: string, celsius: number): string {
  return `${city}: ${celsius}°C is ${toFahrenheit(celsius)}°F`;
}

console.log(describeTemperature("Yangon", 30));
console.log(describeTemperature("Mandalay", 35.5));
// describeTemperature(30, "Yangon"); // Error: number is not assignable to string

Quick quiz 1 / 3

What happens when `let n = 5; n = "five";` is written in a `.ts` file?

Quick quiz 2 / 3

In the example, what does `console.log(typeof message, typeof firstReleased)` print?

Quick quiz 3 / 3

A project runs its code with `tsx`, and there is a type error in it. What happens?

What to remember

  • TypeScript is a superset of JavaScript: it keeps all of its syntax and adds static types
  • Valid JavaScript always parses but may fail the type check, and that is the benefit
  • Types are inferred from initial values, so annotations mostly go on parameters
  • Types are erased by compilation; at run time only JavaScript's `typeof` remains

Announcing TypeScript 7.0 — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is TypeScript? | Thuta Learning