let message: string = "Hello, TypeScript!";
let count: number = 42;
let isActive: boolean = true;
Types
Type
let n: number = 10;
let s: string = "foo";
let b: boolean = false;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ["age", 30];
let u: undefined = undefined;
let nll: null = null;
Type Inference
Inference
let x = 5; // inferred as number
let y = "hi"; // inferred as string
let z = [1, 2, 3]; // inferred as number[]
Functions
Function
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): void => {
console.log(`Hello, ${name}`);
};
Interfaces
Interface
interface User {
name: string;
age: number;
isAdmin?: boolean;
}
const u: User = { name: "Alice", age: 25 };
Type Aliases
Alias
type Point = { x: number; y: number };
const p: Point = { x: 1, y: 2 };
Enums
Enum
enum Direction {
Up,
Down,
Left,
Right,
}
const d: Direction = Direction.Up;
Classes
Class
class Person {
constructor(public name: string, public age: number) {}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const p = new Person("John", 30);
p.greet();
Generics
Generic
function identity(arg: T): T {
return arg;
}
const num = identity(5); // T is number
const str = identity("hello"); // T is string
Union & Intersection
Union/Intersection
type Animal = { name: string; species: string };
type Bird = { name: string; canFly: boolean };
type Fish = { name: string; canSwim: boolean };
type Pet = Animal & (Bird | Fish);
const myPet: Pet = {
name: "Buddy",
species: "Dog",
canSwim: false,
};
Literal Types
Literal
type Status = "pending" | "completed" | "cancelled";
const orderStatus: Status = "completed";
Tuples
Tuple
let user: [string, number] = ["Alice", 123];
let [name, id] = user;
Type Guards
Guard
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).canSwim !== undefined;
}
const myPet: Fish | Bird = {
name: "Nemo",
canSwim: true,
};
if (isFish(myPet)) {
console.log(`${myPet.name} can swim.`);
} else {
console.log(`${myPet.name} cannot swim.`);
}
Type Assertions
Assertion
const element = document.getElementById("my-element");
const myElement = element as HTMLDivElement;
Modules
Module
// myModule.ts
export const PI = 3.14;
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { PI, add } from "./myModule";
console.log(PI);
console.log(add(5, 3));
Namespaces
Namespace
// myNamespace.ts
namespace MyNamespace {
export const PI = 3.14;
export function add(a: number, b: number): number {
return a + b;
}
}
// main.ts
import { MyNamespace } from "./myNamespace";
console.log(MyNamespace.PI);
console.log(MyNamespace.add(5, 3));
Utility Types
Utility
interface User {
name: string;
age: number;
isAdmin?: boolean;
}
type PartialUser = Partial;
type ReadonlyUser = Readonly;
type PickUser = Pick;
type OmitUser = Omit;