Use Optional Parameters

Use Optional Parameters

Don’t write several overloads that differ only in trailing parameters:

/* WRONG */
interface Moment {
  diff(b: MomentComparable): number;
  diff(b: MomentComparable, unitOfTime: string): number;
  diff(b: MomentComparable, unitOfTime: string, round: boolean): number;
}

Do use optional parameters whenever possible:

/* OK */
interface Moment {
  diff(b: MomentComparable, unitOfTime?: string, round?: boolean): number;
}

Note that this collapsing should only occur when all overloads have the same return type.

Why: This is important for two reasons.

TypeScript resolves signature compatibility by seeing if any signature of the target can be invoked with the arguments of the source, and extraneuous arguments are allowed. This code, for example, exposes a bug only when the signature is correctly written using optional parameters:

function fn(x: (a: string, b: number, c: number) => void) { }
var x: Moment;
// When written with overloads, OK -- used first overload
// When written with optionals, correctly an error
fn(x.diff);

The second reason is when a consumer uses the “strict null checking” feature of TypeScript. Because unspecified parameters appear as undefined in JavaScript, it’s usually fine to pass an explicit undefined to a function with optional arguments. This code, for example, should be OK under strict nulls:

var x: Moment;
// When written with overloads, incorrectly an error because of passing 'undefined' to 'string'
// When written with optionals, correctly OK
x.diff(something, someOtherThing ? undefined : "hour");
doc_TypeScript
2016-10-04 19:25:42
Comments
Leave a Comment

Please login to continue.