TypeScript Samples
Essential TypeScript code examples with type safety and Hello World demonstrations
Key Facts
- Category
- Programming Languages
- Items
- 3
- Format Families
- sample
Sample Overview
Essential TypeScript code examples with type safety and Hello World demonstrations This sample set belongs to Programming Languages and can be used to test related workflows inside Elysia Tools.
💻 TypeScript Hello World typescript
🟢 simple
⭐⭐
Basic TypeScript Hello World program with type annotations and syntax examples
⏱️ 15 min
🏷️ typescript, programming, types
Prerequisites:
Basic JavaScript concepts
// TypeScript Hello World Examples
// 1. Basic Hello World with string type annotation
const message: string = "Hello, World!";
console.log(message);
// 2. Hello World function with type annotations
function sayHello(): string {
return "Hello, World!";
}
console.log(sayHello());
// 3. Hello World with parameter types
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("TypeScript"));
console.log(greet("World"));
// 4. Hello World with interface
interface Greeter {
message: string;
greet(): string;
}
class BasicGreeter implements Greeter {
constructor(public message: string = "Hello, World!") {}
greet(): string {
return this.message;
}
}
const greeter: Greeter = new BasicGreeter();
console.log(greeter.greet());
// 5. Hello World with union types
type Greeting = string | number;
function displayGreeting(greeting: Greeting): void {
if (typeof greeting === 'string') {
console.log(greeting);
} else {
console.log(`Greeting number: ${greeting}`);
}
}
displayGreeting("Hello, World!");
displayGreeting(42);
// 6. Hello World with generic types
function createGreeting<T>(value: T): T {
return value;
}
const stringGreeting: string = createGreeting<string>("Hello, World!");
const numberGreeting: number = createGreeting<number>(123);
console.log(stringGreeting);
console.log(numberGreeting);
// 7. Hello World with optional parameters
function personalizedGreeting(name: string, enthusiastic?: boolean): string {
if (enthusiastic) {
return `Hello, ${name}!!!`;
}
return `Hello, ${name}!`;
}
console.log(personalizedGreeting("Alice"));
console.log(personalizedGreeting("Bob", true));
// 8. Hello World with array types
const greetings: string[] = ["Hello", "Hola", "Bonjour", "こんにちは"];
greetings.forEach(greeting => console.log(`${greeting}, World!`));
// 9. Hello World with tuple types
const greetingInfo: [string, string, number] = ["Hello", "World", 2024];
console.log(`${greetingInfo[0]}, ${greetingInfo[1]}! (${greetingInfo[2]})`);
// 10. Hello World with enum types
enum GreetingType {
Formal = "Good day",
Casual = "Hello",
Enthusiastic = "Hey"
}
function createGreetingByType(type: GreetingType, name: string): string {
return `${type}, ${name}!`;
}
console.log(createGreetingByType(GreetingType.Formal, "World"));
console.log(createGreetingByType(GreetingType.Casual, "Everyone"));
// Basic data types with type annotations
const integer: number = 42;
const float: number = 3.14;
const text: string = "TypeScript";
const isActive: boolean = true;
const numbers: number[] = [1, 2, 3, 4, 5];
const person: { name: string; age: number } = { name: "John", age: 30 };
console.log(`Integer: ${integer}, Type: ${typeof integer}`);
console.log(`Text: ${text}, Type: ${typeof text}`);
// Type assertion
const someValue: any = "Hello, World!";
const strLength: number = (someValue as string).length;
console.log(`String length: ${strLength}`);
// Function with return type annotation
function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(`5 + 3 = ${addNumbers(5, 3)}`);
// Void function
function logMessage(message: string): void {
console.log(message);
}
logMessage("This is a void function");
// Never type (function that never returns)
function throwError(message: string): never {
throw new Error(message);
}
// Type inference (TypeScript can infer types)
let inferredString = "TypeScript infers this as string";
let inferredNumber = 100;
console.log(`Inferred string: ${inferredString}`);
console.log(`Inferred number: ${inferredNumber}`);
💻 TypeScript Interfaces and Types typescript
🟡 intermediate
⭐⭐⭐⭐
Advanced TypeScript interfaces, type aliases, and utility types
⏱️ 25 min
🏷️ typescript, types, interfaces
Prerequisites:
Basic TypeScript syntax
// TypeScript Interfaces and Types Examples
// 1. Basic Interface
interface Person {
name: string;
age: number;
email?: string; // Optional property
readonly id: number; // Read-only property
}
const person: Person = {
name: "Alice",
age: 30,
id: 1
};
// 2. Interface with methods
interface Vehicle {
brand: string;
model: string;
start(): void;
stop(): void;
}
class Car implements Vehicle {
constructor(
public brand: string,
public model: string
) {}
start(): void {
console.log(`${this.brand} ${this.model} started`);
}
stop(): void {
console.log(`${this.brand} ${this.model} stopped`);
}
}
const myCar: Vehicle = new Car("Toyota", "Corolla");
myCar.start();
myCar.stop();
// 3. Interface extending
interface Animal {
name: string;
makeSound(): void;
}
interface Dog extends Animal {
breed: string;
wagTail(): void;
}
class Labrador implements Dog {
constructor(
public name: string,
public breed: string = "Labrador"
) {}
makeSound(): void {
console.log("Woof!");
}
wagTail(): void {
console.log("Tail wagging happily");
}
}
const dog: Dog = new Labrador("Max");
dog.makeSound();
dog.wagTail();
// 4. Type Aliases
type ID = string | number;
type Coordinates = [number, number]; // Tuple type
type Status = "pending" | "completed" | "failed";
type User = {
id: ID;
name: string;
status: Status;
location: Coordinates;
};
const user: User = {
id: "user123",
name: "John Doe",
status: "pending",
location: [40.7128, -74.0060]
};
// 5. Generic Interfaces
interface Repository<T> {
findById(id: string): T | null;
save(entity: T): void;
delete(id: string): boolean;
}
interface Product {
id: string;
name: string;
price: number;
}
class ProductRepository implements Repository<Product> {
private products: Product[] = [];
findById(id: string): Product | null {
return this.products.find(p => p.id === id) || null;
}
save(entity: Product): void {
const existing = this.findById(entity.id);
if (existing) {
Object.assign(existing, entity);
} else {
this.products.push(entity);
}
}
delete(id: string): boolean {
const index = this.products.findIndex(p => p.id === id);
if (index > -1) {
this.products.splice(index, 1);
return true;
}
return false;
}
}
// 6. Utility Types
interface Book {
id: string;
title: string;
author: string;
price: number;
published: boolean;
}
// Partial - makes all properties optional
type BookUpdate = Partial<Book>;
// Required - makes all properties required
type RequiredBook = Required<Book>;
// Pick - select specific properties
type BookInfo = Pick<Book, 'title' | 'author'>;
// Omit - remove specific properties
type BookWithoutPrice = Omit<Book, 'price'>;
// Record - create object type with specific keys and values
type BookCatalog = Record<string, Book>;
// 7. Function Types
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;
console.log(`Add: ${add(5, 3)}`);
console.log(`Multiply: ${multiply(5, 3)}`);
// 8. Index Signatures
interface StringArray {
[index: number]: string;
}
const names: StringArray = ["Alice", "Bob", "Charlie"];
interface Dictionary {
[key: string]: number;
}
const ages: Dictionary = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
};
// 9. Mapped Types
type Optional<T> = {
[P in keyof T]?: T[P];
};
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type ReadonlyBook = Readonly<Book>;
// 10. Conditional Types
type NonNullable<T> = T extends null | undefined ? never : T;
type ExtractType<T, U> = T extends U ? T : never;
type ExtractString = ExtractType<string | number | boolean, string>;
// Type predicates
function isString(value: any): value is string {
return typeof value === 'string';
}
function processValue(value: any) {
if (isString(value)) {
console.log(`String value: ${value.toUpperCase()}`);
} else {
console.log(`Non-string value: ${value}`);
}
}
processValue("hello");
processValue(42);
// 11. Declaration Merging
interface UserSettings {
theme: string;
}
interface UserSettings {
notifications: boolean;
}
const settings: UserSettings = {
theme: "dark",
notifications: true
};
// 12. Mixed types example
type ApiResponse<T> = {
data: T;
status: number;
message: string;
};
interface ApiResponseHandler<T> {
handleResponse(response: ApiResponse<T>): void;
}
class UserApiHandler implements ApiResponseHandler<User> {
handleResponse(response: ApiResponse<User>): void {
console.log(`User: ${response.data.name}, Status: ${response.status}`);
}
}
💻 TypeScript Classes and Advanced OOP typescript
🟡 intermediate
⭐⭐⭐⭐
Object-oriented programming in TypeScript with classes, inheritance, and decorators
⏱️ 30 min
🏷️ typescript, oop, classes
Prerequisites:
Basic TypeScript syntax and interfaces
// TypeScript Classes and Advanced OOP Examples
// 1. Basic Class with Access Modifiers
class Employee {
// Properties with access modifiers
public id: number;
private name: string;
protected department: string;
readonly company: string = "Tech Corp";
constructor(id: number, name: string, department: string) {
this.id = id;
this.name = name;
this.department = department;
}
// Public method
public getDetails(): string {
return `${this.name} (ID: ${this.id}) - ${this.department}`;
}
// Private method
private calculateSalary(): number {
return 50000 + (this.id * 1000);
}
// Protected method
protected getDepartmentInfo(): string {
return `Department: ${this.department}`;
}
}
// 2. Class Inheritance
class Manager extends Employee {
private teamSize: number;
constructor(id: number, name: string, department: string, teamSize: number) {
super(id, name, department);
this.teamSize = teamSize;
}
public getManagerDetails(): string {
return `${this.getDetails()} - Team Size: ${this.teamSize}`;
}
// Overriding method
public getDetails(): string {
return `${super.getDetails()} [MANAGER]`;
}
// Accessing protected member from parent
public getFullInfo(): string {
return `${this.getDetails()} - ${this.getDepartmentInfo()}`;
}
}
const manager = new Manager(1, "Alice", "Engineering", 10);
console.log(manager.getManagerDetails());
// 3. Abstract Classes
abstract class Shape {
constructor(protected color: string) {}
abstract getArea(): number;
abstract getPerimeter(): number;
public getColor(): string {
return this.color;
}
public printInfo(): void {
console.log(`Shape color: ${this.color}`);
}
}
class Circle extends Shape {
constructor(
color: string,
private radius: number
) {
super(color);
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
getPerimeter(): number {
return 2 * Math.PI * this.radius;
}
}
class Rectangle extends Shape {
constructor(
color: string,
private width: number,
private height: number
) {
super(color);
}
getArea(): number {
return this.width * this.height;
}
getPerimeter(): number {
return 2 * (this.width + this.height);
}
}
const circle = new Circle("red", 5);
const rectangle = new Rectangle("blue", 4, 6);
// 4. Static Members
class MathHelper {
private static PI: number = 3.14159;
public static calculateCircleArea(radius: number): number {
return this.PI * radius * radius;
}
public static calculateCircleCircumference(radius: number): number {
return 2 * this.PI * radius;
}
public static getVersion(): string {
return "1.0.0";
}
}
console.log(`Circle area: ${MathHelper.calculateCircleArea(5)}`);
console.log(`MathHelper version: ${MathHelper.getVersion()}`);
// 5. Getters and Setters
class BankAccount {
private _balance: number = 0;
get balance(): number {
return this._balance;
}
set balance(amount: number) {
if (amount < 0) {
throw new Error("Balance cannot be negative");
}
this._balance = amount;
}
public deposit(amount: number): void {
if (amount > 0) {
this._balance += amount;
}
}
public withdraw(amount: number): void {
if (amount > 0 && amount <= this._balance) {
this._balance -= amount;
}
}
}
const account = new BankAccount();
account.balance = 1000;
console.log(`Account balance: ${account.balance}`);
// 6. Implementing Multiple Interfaces
interface Loggable {
log(): void;
}
interface Serializable {
serialize(): string;
}
class User implements Loggable, Serializable {
constructor(
public id: number,
public name: string,
public email: string
) {}
log(): void {
console.log(`User: ${this.name} (${this.email})`);
}
serialize(): string {
return JSON.stringify({
id: this.id,
name: this.name,
email: this.email
});
}
static deserialize(data: string): User {
const obj = JSON.parse(data);
return new User(obj.id, obj.name, obj.email);
}
}
const user = new User(1, "John Doe", "[email protected]");
user.log();
const serialized = user.serialize();
console.log(`Serialized: ${serialized}`);
// 7. Class Decorators
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class SealedClass {
constructor(public message: string) {}
}
// Property Decorator
function format(formatString: string) {
return function (target: any, propertyKey: string) {
let value: string;
const getter = function() {
return value;
};
const setter = function(newVal: string) {
value = formatString.replace(/{0}/g, newVal);
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
};
}
class GreetingService {
@format("Hello, {0}!")
private name: string = "";
constructor(name: string) {
this.name = name;
}
public getGreeting(): string {
return this.name;
}
}
const greeting = new GreetingService("World");
console.log(greeting.getGreeting()); // "Hello, World!"
// 8. Mixins
class Timestamped {
private timestamp: number = Date.now();
public getTimestamp(): number {
return this.timestamp;
}
}
class Activatable {
private isActive: boolean = false;
public activate(): void {
this.isActive = true;
}
public deactivate(): void {
this.isActive = false;
}
public getActiveStatus(): boolean {
return this.isActive;
}
}
// Apply mixins
interface SmartObject extends Timestamped, Activatable {}
class SmartObject {
public getTimestamp!: () => number;
public activate!: () => void;
public deactivate!: () => void;
public getActiveStatus!: () => boolean;
constructor(public id: string, public name: string) {}
}
// Apply mixin functionality
Object.assign(SmartObject.prototype, Timestamped.prototype, Activatable.prototype);
const smartObj = new SmartObject("obj1", "Smart Device");
console.log(`Timestamp: ${smartObj.getTimestamp()}`);
smartObj.activate();
console.log(`Active: ${smartObj.getActiveStatus()}`);
// 9. Generic Classes
class Container<T> {
private items: T[] = [];
public addItem(item: T): void {
this.items.push(item);
}
public removeItem(item: T): boolean {
const index = this.items.indexOf(item);
if (index > -1) {
this.items.splice(index, 1);
return true;
}
return false;
}
public getItems(): T[] {
return [...this.items];
}
public findItem(predicate: (item: T) => boolean): T | undefined {
return this.items.find(predicate);
}
}
const stringContainer = new Container<string>();
stringContainer.addItem("Hello");
stringContainer.addItem("World");
console.log(stringContainer.getItems());
// 10. Singleton Pattern
class DatabaseConnection {
private static instance: DatabaseConnection;
private connection: any;
private constructor() {
this.connection = "Database connection established";
}
public static getInstance(): DatabaseConnection {
if (!DatabaseConnection.instance) {
DatabaseConnection.instance = new DatabaseConnection();
}
return DatabaseConnection.instance;
}
public query(sql: string): void {
console.log(`Executing: ${sql}`);
console.log(`Using: ${this.connection}`);
}
}
const db1 = DatabaseConnection.getInstance();
const db2 = DatabaseConnection.getInstance();
console.log(`Same instance: ${db1 === db2}`);
db1.query("SELECT * FROM users");