Functions
TypeScript allows you to annotate function parameters and return types.
Parameter and Return Types
function add(a: number, b: number): number {
return a + b
}
const greet = (name: string): string => {
return \`Hello, \${name}!\`
}
// Void — no return value
function log(message: string): void {
console.log(message)
}
Optional Parameters
function greet(name: string, greeting?: string): string {
return \`\${greeting ?? 'Hello'}, \${name}!\`
}
greet('Alice') // 'Hello, Alice!'
greet('Alice', 'Hi') // 'Hi, Alice!'
Default Parameters
function repeat(str: string, times: number = 3): string {
return str.repeat(times)
}
repeat('ha') // 'hahaha'
repeat('ha', 2) // 'haha'
Overloads
function format(value: string): string
function format(value: number): string
function format(value: string | number): string {
return String(value)
}