iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Parameters

TypeScript supports every JavaScript parameter shape — positional, optional, default, rest, destructured — and types each one.

Positional & default

TS
function paginate(items: unknown[], page = 1, size = 20) {
    const start = (page - 1) * size;
    return items.slice(start, start + size);
}

Optional

TS
function greet(name: string, title?: string) {
    return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
// Optional must come AFTER required ones.

Object parameters (named arguments)

TS
type ReserveOpts = {
    name: string;
    table: number;
    time: string;
    party?: number;
};

function reserve({ name, table, time, party = 2 }: ReserveOpts) {
    console.log(`${party} for ${name} at ${time}`);
}

reserve({ name: 'Ada', table: 7, time: '19:00' });

Rest parameters

TS
function tag(strings: TemplateStringsArray, ...vals: unknown[]) {
    return strings.reduce(
        (out, s, i) => out + s + (vals[i] ?? ''),
        '',
    );
}

"this" parameter

TS
interface Counter {
    count: number;
    bump(this: Counter): void;
}

const c: Counter = {
    count: 0,
    bump() {
        this.count++;       // this typed as Counter
    },
};

Parameter destructuring with type aliases

TS
function format({ year, month = 1, day = 1 }: { year: number; month?: number; day?: number }) {
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}
Tip: If a function takes more than 3 parameters, switch to an options object — named arguments survive future additions and let callers skip optional ones in any order.

Example

Example
function greet(name: string, title?: string, exclaim = false): string {
  const prefix = title ? `${title} ` : '';
  return `Hello, ${prefix}${name}${exclaim ? '!' : ''}`;
}
console.log(greet('Ada'));
console.log(greet('Lovelace', 'Dr.', true));
Try it Yourself »

Exercise

Rest parameter that collects all extra args.

function avg( nums: number[]) {}

Test yourself

Q1. Optional parameters use…
Q2. Optional parameters must come…
Q3. For 4+ parameters prefer…

Discussion

Loading…