Here's the modified TypeScript function that can return either a Department object or null:
typescript
interface Department {
id: number;
name: string;
managerId: number;
employeeCount: number;
budget: number;
}
function getDepartment(id: number): Department | null {
// Example logic: return null if department doesn't exist
if (id <= 0) {
return null;
}
// Return department object if found
return {
id: id,
name: "Engineering",
managerId: 101,
employeeCount: 25,
budget: 1500000
};
}
For a more realistic example with a lookup:
typescript
function findDepartment(id: number): Department | null {
const departments: Department[] = [
{ id: 1, name: "Engineering", managerId: 101, employeeCount: 25, budget: 1500000 },
{ id: 2, name: "Sales", managerId: 102, employeeCount: 15, budget: 800000 },
{ id: 3, name: "Marketing", managerId: 103, employeeCount: 10, budget: 500000 }
];
const department = departments.find(dept => dept.id === id);
return department || null;
}
// Usage:
const dept = findDepartment(1); // Returns Department object
const notFound = findDepartment(99); // Returns null
For an async version:
typescript
async function fetchDepartment(departmentId: number): Promise<Department | null> {
try {
const response = await fetch(`/api/departments/${departmentId}`);
if (!response.ok) {
return null;
}
const data: Department = await response.json();
return data;
} catch (error) {
return null;
}
}