Is there any difference in using overloads or optional parameters in TypeScript?

typescript

Solution

From a type compatibility perspective, these are indistinguishable in practice.

However, the second version is slightly better because only functions with a single overload can apply a contextual type. For example:

interface Read1 {
    readText(fileName: string, def: string): any;
    readText(fileName: string): any;
}
// No contextual type applied because readText has multiple signatures
// 's' of type 'any', no error raised
var x: Read1 = { readText: (s) => s.subtring(s) };
interface Read2 {
    readText(fileName: string, def?: string): any;
}
// Contextual type applied
// 's' of type 'string', error identified
var y: Read2 = { readText: (s) => s.subtring(s) };

Problem

I was wondering if there is any difference in the following code blocks? The first creates 2 definitions of the readText function. I would write it in the second way, with an optional parameter. ``` readText(fileName: string, def: string): WinJS.Promise; readText(fileName: string): WinJS.Promise; ``` and ``` readText(fileName: string, def?: string): WinJS.Promise; ``` Is there any reason not to use the optional parameter?

Original source