Learn TYPESCRIPT with Real Code Examples
Updated Nov 17, 2025
Code Sample Descriptions
TypeScript Theme Toggle and Counter
document.addEventListener('DOMContentLoaded', () => {
const counterEl = document.getElementById('counter') as HTMLElement;
const incrementBtn = document.getElementById('increment') as HTMLButtonElement;
const decrementBtn = document.getElementById('decrement') as HTMLButtonElement;
const resetBtn = document.getElementById('reset') as HTMLButtonElement;
const toggleThemeBtn = document.getElementById('toggleTheme') as HTMLButtonElement;
const appEl = document.getElementById('app') as HTMLElement;
let count: number = parseInt(localStorage.getItem('count') || '0', 10);
let isDark: boolean = localStorage.getItem('isDark') === 'true';
const updateUI = (): void => {
counterEl.textContent = `Counter: ${count}`;
appEl.className = isDark ? 'dark-theme' : 'light-theme';
toggleThemeBtn.textContent = `Switch to ${isDark ? 'Light' : 'Dark'} Theme`;
};
incrementBtn.addEventListener('click', () => { count++; saveAndUpdate(); });
decrementBtn.addEventListener('click', () => { count--; saveAndUpdate(); });
resetBtn.addEventListener('click', () => { count = 0; saveAndUpdate(); });
toggleThemeBtn.addEventListener('click', () => { isDark = !isDark; saveAndUpdate(); });
function saveAndUpdate(): void {
localStorage.setItem('count', count.toString());
localStorage.setItem('isDark', isDark.toString());
updateUI();
}
updateUI();
});
Demonstrates state management, DOM manipulation, localStorage, and theme toggling using TypeScript with proper typing.
TypeScript Form Validation
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('form') as HTMLFormElement;
const username = document.getElementById('username') as HTMLInputElement;
const email = document.getElementById('email') as HTMLInputElement;
form.addEventListener('submit', (e) => {
e.preventDefault();
if(username.value.trim() === '') alert('Username required');
if(email.value.trim() === '') alert('Email required');
});
});
Validates form inputs, prevents submission if invalid, and shows error messages.
TypeScript To-Do List
document.addEventListener('DOMContentLoaded', () => {
interface Todo { task: string; done: boolean; }
let todos: Todo[] = [];
const input = document.getElementById('task') as HTMLInputElement;
const addBtn = document.getElementById('add') as HTMLButtonElement;
const list = document.getElementById('list') as HTMLElement;
addBtn.addEventListener('click', () => {
if(input.value.trim() === '') return;
todos.push({task: input.value, done: false});
input.value = '';
render();
});
function render() {
list.innerHTML = '';
todos.forEach((t, i) => {
const li = document.createElement('li');
li.textContent = t.task;
li.style.textDecoration = t.done ? 'line-through' : 'none';
li.addEventListener('click', () => { todos[i].done = !todos[i].done; render(); });
list.appendChild(li);
});
}
});
Implements a simple to-do list with add, delete, and toggle completed functionality using TypeScript.
TypeScript Modal Example
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('modal') as HTMLElement;
const openBtn = document.getElementById('open') as HTMLButtonElement;
const closeBtn = document.getElementById('close') as HTMLButtonElement;
openBtn.addEventListener('click', () => { modal.style.display = 'block'; });
closeBtn.addEventListener('click', () => { modal.style.display = 'none'; });
});
Shows opening and closing a modal with proper type-safe event handling.
TypeScript Fetch API Example
document.addEventListener('DOMContentLoaded', () => {
const output = document.getElementById('output') as HTMLElement;
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(data => { output.textContent = JSON.stringify(data); })
.catch(err => console.error(err));
});
Fetches data from an API, parses JSON, and renders results in the DOM.
TypeScript Tabs Navigation
document.addEventListener('DOMContentLoaded', () => {
const tabs = document.querySelectorAll('.tab') as NodeListOf<HTMLButtonElement>;
const contents = document.querySelectorAll('.content') as NodeListOf<HTMLElement>;
tabs.forEach((tab, idx) => {
tab.addEventListener('click', () => {
contents.forEach(c => c.style.display = 'none');
contents[idx].style.display = 'block';
});
});
});
Implements tab navigation with type-safe event handling and dynamic content switching.
TypeScript Image Slider
document.addEventListener('DOMContentLoaded', () => {
const images = document.querySelectorAll('.slide') as NodeListOf<HTMLImageElement>;
let index = 0;
const nextBtn = document.getElementById('next') as HTMLButtonElement;
const prevBtn = document.getElementById('prev') as HTMLButtonElement;
function show(i: number) {
images.forEach(img => img.style.display = 'none');
images[i].style.display = 'block';
}
nextBtn.addEventListener('click', () => { index = (index + 1) % images.length; show(index); });
prevBtn.addEventListener('click', () => { index = (index - 1 + images.length) % images.length; show(index); });
show(index);
});
Creates a simple image slider with next/previous buttons.
TypeScript Countdown Timer
document.addEventListener('DOMContentLoaded', () => {
const display = document.getElementById('display') as HTMLElement;
const startBtn = document.getElementById('start') as HTMLButtonElement;
const stopBtn = document.getElementById('stop') as HTMLButtonElement;
let time = 10;
let timer: number;
startBtn.addEventListener('click', () => { timer = window.setInterval(() => { display.textContent = time.toString(); time--; if(time < 0) clearInterval(timer); }, 1000); });
stopBtn.addEventListener('click', () => clearInterval(timer));
});
Implements a countdown timer with start, stop, and reset buttons.
TypeScript Drag and Drop Example
document.addEventListener('DOMContentLoaded', () => {
const draggable = document.getElementById('drag') as HTMLElement;
const dropzone = document.getElementById('drop') as HTMLElement;
draggable.addEventListener('dragstart', (e) => { e.dataTransfer?.setData('text', 'dragged'); });
dropzone.addEventListener('dragover', (e) => e.preventDefault());
dropzone.addEventListener('drop', (e) => { e.preventDefault(); dropzone.textContent = 'Dropped!'; });
});
Enables dragging and dropping of elements with proper TypeScript types.
TypeScript Modal with Async Data
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('modal') as HTMLElement;
const openBtn = document.getElementById('open') as HTMLButtonElement;
const content = document.getElementById('content') as HTMLElement;
openBtn.addEventListener('click', async () => {
modal.style.display = 'block';
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
content.textContent = data.title;
});
});
Opens a modal and loads async content from an API when the modal opens.