TypeScript Basics

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

Illustration of TypeScript Basics
Illustration of TypeScript Basics

💡 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 values
  • string: for text
  • boolean: true or false
  • any: disables type checking (use sparingly)
  • void: for functions that don't return a value
  • null and undefined: represent absence of value

Declaring Variables with Types

Use let or const with a type annotation to declare variables:

📌 Deep Dive: Variable Type Annotations

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
let id: number | string;
id = 123;      // valid
id = "ABC123"; // valid
TypeScript vs JavaScript Variable Declaration
JavaScriptTypeScript
let age = 30;let age: number = 30;
function greet(name) { ... }function greet(name: string): string { ... }
Objects have no enforced shapeUse 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.