Typed Functions
Level: Beginner
- Function parameter typing and annotations
- Return type declarations
- Optional and default parameters
- Rest parameters (...args)
- Function overloading signatures
- Arrow functions with type annotations
- Callback function types
- SMS service method signatures
Why This Matters
Typed Functions helps you write safer frontend code. In ASP.NET Core projects, TypeScript makes API response shapes, form models, DOM values, and reusable helpers easier to maintain.
Define function parameters and return types.
The Problem
JavaScript allows many mistakes to appear only at runtime. This lesson shows how Typed Functions lets TypeScript catch wrong values, missing properties, and unsafe assumptions before the page reaches users.
Basic Function Typing
// Parameters and return type
function add(a: number, b: number): number {
return a + b;
}
const result = add(5, 3); // OK, result is number
const bad = add("5", "3"); // Error - wrong type
Optional Parameters
function greet(name: string, title?: string): string {
if (title) {
return `Hello ${title} ${name}`;
}
return `Hello ${name}`;
}
greet("Ravi"); // OK
greet("Ravi", "Dr."); // OK
Default Parameters
function registerStudent(
name: string,
className: string = "10",
status: string = "Active"
): void {
console.log(`${name} in class ${className} is ${status}`);
}
registerStudent("Ravi"); // Uses defaults
registerStudent("Ravi", "11"); // Override some
registerStudent("Ravi", "11", "Inactive"); // Override all
Return Types
// Returns object
function getStudent(id: number): { name: string; email: string } {
return {
name: "Ravi Kumar",
email: "ravi@example.com"
};
}
// Returns array
function getMarks(studentId: number): number[] {
return [95, 88, 92];
}
// Returns nothing
function logMessage(message: string): void {
console.log(message);
}
// Returns union type
function getStatus(isActive: boolean): "Active" | "Inactive" {
return isActive ? "Active" : "Inactive";
}
Function with Interface
interface Student {
id: number;
name: string;
email: string;
}
function updateStudent(id: number, data: Student): void {
console.log(`Updated student ${data.name}`);
}
updateStudent(101, {
id: 101,
name: "Ravi Kumar",
email: "ravi@example.com"
});
Arrow Functions
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;
const result = multiply(5, 3); // 15
// With parameters and return
const calculatePercentage = (obtained: number, total: number): number => {
return (obtained / total) * 100;
};
const percentage = calculatePercentage(85, 100); // 85
Function Types
// Define function signature as type
type StudentValidator = (data: any) => boolean;
const isValidStudent: StudentValidator = (data) => {
return data.name && data.email && data.className;
};
const valid = isValidStudent({
name: "Ravi",
email: "ravi@example.com",
className: "10"
});
Async Functions
// Async returns Promise
async function fetchStudent(id: number): Promise<Student> {
const response = await fetch(`/api/students/${id}`);
const student: Student = await response.json();
return student;
}
// Usage
const student = await fetchStudent(101);
REST Parameters
// Accept variable number of arguments
function sumMarks(...marks: number[]): number {
return marks.reduce((a, b) => a + b, 0);
}
const total = sumMarks(95, 88, 92, 87); // 362
SMS Example
interface StudentData {
rollNumber: string;
name: string;
email: string;
className: string;
}
// Register student
async function registerStudent(
data: StudentData
): Promise<{ success: boolean; studentId: number }> {
const response = await fetch('/api/students', {
method: 'POST',
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Registration failed');
}
return response.json();
}
// Update student
function updateStudentStatus(
studentId: number,
status: "Active" | "Inactive"
): void {
console.log(`Student ${studentId} status: ${status}`);
// Send to API
}
// Validate marks
function isPassingMarks(marks: number, passingMarks: number = 40): boolean {
return marks >= passingMarks;
}
const pass = isPassingMarks(85, 40); // true
Key Takeaways
- Type parameters and return values
- Optional and default parameters
- Return types (objects, arrays, void)
- Arrow function syntax
- Async functions return Promise
- Next: Classes and constructors
Match function signatures with API contracts. If API expects { name, email, className }, type the function parameter exactly.
- Missing parameter types — TypeScript can't validate
- Wrong return type — Returns different type than declared
- Forgetting Promise for async — Return type should be Promise
- Not using void — Functions with no return should say void
Use ChatGPT, Claude, or Copilot to go deeper on TypeScript Functions. Try these prompts:
"Why type function parameters?""What's difference between optional and default?""How do you type async functions?""Quiz me on function types"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
Quick Definitions
- Typed Functions - The main TypeScript concept explained in this lesson.
- Type - A rule that describes what kind of value is allowed.
- Interface - A contract that describes the shape of an object.
- DTO model - The frontend shape of data coming from ASP.NET Core Web API.
Common Mistakes
- Using
anyinstead of defining a useful type - Making types too complex before understanding the data
- Forgetting that API data still needs runtime validation
- Confusing JavaScript runtime behavior with TypeScript compile-time checks
- Not reusing shared types for repeated API models
Practice Task
Create a small TypeScript example using Typed Functions. Keep it connected to a School Management System scenario.
Suggested practice:
- Define a
Student,Teacher,Attendance, orMarksmodel. - Write one function or class using that type.
- Add one intentionally wrong value and read the TypeScript error.
- Fix the type or the data shape.
- Explain the type contract in your own words.
Quick Revision
| Question | Answer |
|---|---|
| What is the main idea? | Use TypeScript to make Typed Functions safer and clearer. |
| Where is it used? | API models, forms, DOM code, helpers, and React/Next.js apps. |
| What should beginners avoid? | Overusing any and ignoring API validation. |
| What is the best debugging habit? | Read the TypeScript error and compare it with the expected data shape. |
Typed Functions is a TypeScript concept that improves JavaScript safety by making data shapes and function expectations clear. I would explain the problem it solves, show a small example, and mention how it helps with API-connected frontend code.
It is used in API DTOs, form models, DOM access, helper functions, React props, service classes, and reusable frontend utilities.