TS Functions
Functions are where annotations earn their keep — typing parameters and returns turns "what does this do?" into compiler-checked contracts.
Basics
TS
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): string => `Hi, ${name}`;
const log: (msg: string) => void = msg => console.log(msg);
Inferred return types
TS infers the return type from the body. You only need to write it down when:
- The function is exported from a module (stable API).
- The body is complex enough that you want a guarantee.
- You're using generics and want to keep the inference predictable.
Optional & default parameters
TS
function greet(name: string, title?: string, exclaim = false): string {
const prefix = title ? `${title} ` : '';
return `Hello, ${prefix}${name}${exclaim ? '!' : ''}`;
}
Rest parameters
TS
function average(...nums: number[]): number {
return nums.reduce((c, n) => c + n, 0) / nums.length;
}
console.log(average(1, 2, 3, 4)); // 2.5
Function as type
TS
type Comparator<T> = (a: T, b: T) => number;
const byAge: Comparator<{ age: number }> = (a, b) => a.age - b.age;
Methods on object types
TS
type Greeter = {
greet(name: string): string;
};
const g: Greeter = {
greet(name) { return `Hi, ${name}`; },
};
Tip: Annotate parameter types and the return type on every exported function. Skip both on internal callbacks where context already supplies them.
Example
Example
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): string => `Hello, ${name}!`;
console.log(add(2, 3), greet('Ada'));
Try it Yourself »
Exercise
Arrow function returning a string greeting.
const g = (name: string): string
`Hi, ${name}`;
Arrow — equals + greater-than.
Discussion
Loading…