Functions are one of the most common places to use TypeScript types. Parameter types, return types, and async return types should usually be explicit.
Basic Function Types
function calculateDiscount(price: number, rate: number): number {
return price * rate;
}Return types can often be inferred, but public or complex functions are clearer with explicit return types.
Default Parameters
function calculateDiscount(price: number, rate: number = 0.5): number {
return price * rate;
}
calculateDiscount(1000);
calculateDiscount(1000, 0.3);Default parameters reduce repeated configuration.
Rest Parameters
function joinNames(prefix: string, ...names: string[]): string {
return `${prefix}: ${names.join(", ")}`;
}...names means the function accepts any number of string arguments.
Promise Basics
Async functions usually return Promise<T>.
async function fetchUser(): Promise<{ id: string; name: string }> {
return { id: "1", name: "Alice" };
}async automatically wraps returned values in a Promise.
await
await waits for a Promise to resolve.
async function main() {
try {
const user = await fetchUser();
console.log(user.name);
} catch (error) {
console.error("Failed to fetch user", error);
}
}Practical Advice
For async service functions, make return values explicit.
async function pullContacts(args: {
limit?: number;
page?: number;
}): Promise<ContactList> {
return { contacts: [] };
}This gives callers better type hints and catches interface changes earlier.