Quick Overview
TypeScript erases entirely at build time, so a `string` annotation produces no runtime check whatsoever. A value arriving from an API is whatever the server actually sent, regardless of what the annotation claims.
JavaScript is dynamically typed, meaning variables can change their data type at runtime without warning. TypeScript extends JavaScript by adding a compile-time type system that catches type mismatch bugs before your code ever runs in production.
A type annotation uses a colon (:) followed by the type name after a variable declaration:
const username: string = "Alex";
const userAge: number = 28;
const isPremiumUser: boolean = true;
const secretKey: symbol = Symbol("auth");
const bigQuantity: bigint = 9007199254740991n;
// Function parameters with explicit types
function formatUser(name: string, age: number): string {
return `User: ${name}, Age: ${age}`;
}
console.log(formatUser(username, userAge));
TypeScript types exist ONLY during development and compilation. They are completely erased when compiling down to plain JavaScript:
[ TypeScript Layer (Compile Time) ] ──> Type Checking & IDE Autocomplete
│ (Type Erasure)
▼
[ JavaScript Layer (Runtime Time) ] ──> Executable V8 Engine Code
In TypeScript, null and undefined have their own distinct types:
let pendingData: undefined = undefined;
let emptyRef: null = null;
const x: number = 5) adds visual noise. Let TypeScript infer obvious primitives automatically!String or Number instead of lowercase primitive types (string, number) refers to JavaScript object wrapper classes, not primitive values. Always use lowercase type annotations.Explicit type annotations define clear contracts. Next, let's explore Automatic Type Inference and Const Assertions!
`let x = "GET"` infers `string` because the binding can change; `const x = "GET"` infers the literal `"GET"`. That widening rule is why object properties need `as const` to stay narrow.
`string[]` is any number of strings; `[string, number]` is exactly two, in that order. `readonly` removes the mutating methods at compile time, so `push` becomes a type error rather than a runtime surprise.
`?` makes a property optional, which adds `undefined` to its type rather than removing the key. That is why reading it still needs a check even after the shape is declared.
Average 5.0 by 1 learner