Functions
Typed parameters and return values, optional and default parameters, and function types.
Runs in Zerethon IDE · TypeScript 7
Official TypeScript documentation ↗
main.ts
function greet(name: string, greeting = 'Hello'): string {
return `${greeting}, ${name}!`;
}
function label(name: string, title?: string): string {
return title ? `${title} ${name}` : name;
}
const apply = (values: number[], fn: (n: number) => number): number[] => values.map(fn);
console.log(greet('Ada'), greet('Linus', 'Hi'));
console.log(label('Ada'), label('Lovelace', 'Countess'));
console.log(apply([1, 2, 3], (n) => n * 10));
Output
Hello, Ada! Hi, Linus! Ada Countess Lovelace [ 10, 20, 30 ]
- Parameters need types (strict mode reports an implicit
any); the return type is inferred but writing it documents the function. title?: stringis optional — inside the function its type isstring | undefined.voidis the return type of a function that returns nothing.