TypeScript is a superset of JavaScript that adds static typing to the language. It helps catch errors early and improves code maintainability.

💡 What is TypeScript?
TypeScript extends JavaScript by adding optional static types, enabling better tooling and error detection during development.
Basic Types in TypeScript
Here are some common primitive types you will use:
number: for all numeric valuesstring: for textboolean: true or falseany: disables type checking (use sparingly)void: for functions that don't return a valuenullandundefined: represent absence of value
Declaring Variables with Types
Use let or const with a type annotation to declare variables:
📌 Deep Dive: Variable Type Annotations
let age: number = 30;
const name: string = "Alice";
let isStudent: boolean = false;
💡 Type Inference
If you initialize a variable when declaring it, TypeScript infers the type automatically:
let count = 10; infers count as number.
Functions with Typed Parameters and Return Types
Specify types for function parameters and the return value to avoid mistakes:
📌 Deep Dive: Typed Functions
function greet(name: string): string {
return "Hello, " + name;
}
Interfaces: Defining Object Shapes
Use interface to define the expected structure of an object:
📌 Deep Dive: Interface Example
interface Person {
name: string;
age: number;
}
const user: Person = {
name: "Bob",
age: 25
};
⚠️ Type Safety Reminder
TypeScript will throw errors if you assign values that don't match the declared types. This helps prevent bugs early!
Union Types
Allow a variable to hold one of several types by using |:
📌 Deep Dive: Union Types
let id: number | string;
id = 123; // valid
id = "ABC123"; // valid
| JavaScript | TypeScript |
|---|---|
let age = 30; | let age: number = 30; |
function greet(name) { ... } | function greet(name: string): string { ... } |
| Objects have no enforced shape | Use interface to enforce object structure |
💡 Summary
- TypeScript adds static typing to JavaScript.
- Declare variable types using annotations or rely on inference.
- Functions can have typed parameters and return values.
- Interfaces define object shapes for better code clarity.
- Union types allow variables to hold multiple types.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which TypeScript type allows a variable to hold either a number or a string?
Question 2 of 2
What is the purpose of an interface in TypeScript?
Loading results...