Skip to content

Instantly share code, notes, and snippets.

@seahindeniz
Last active September 23, 2022 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seahindeniz/4de7ad774c1043ddb47b4080667bb06a to your computer and use it in GitHub Desktop.
Save seahindeniz/4de7ad774c1043ddb47b4080667bb06a to your computer and use it in GitHub Desktop.
JSDoc for class method, overloading, adding multiple signatures.
/**
* @typedef {(x: number) => string} NumberToStringType
*
* @typedef {(x: string) => number} StringToNumberType
*
* @typedef {NumberToStringType & StringToNumberType} FlipType
*/
class SampleClass {
constructor() {
/**
* @type {FlipType}
*/
this.flip = this._flip;
}
/**
* @type {FlipType}
* The @type definition will not effect here
*/
_flip(x) {
if (typeof x === 'string')
return Number(x);
else
return String(x);
}
}
let sample = new SampleClass();
let number1 = sample.flip(1); // string
let string1 = sample.flip("1"); // number
let number2 = sample._flip(2); // string | number
let string2 = sample._flip("2"); // string | number
/**
* Arrow function
*
* @type {FlipType}
*/
const flipper = x => {
if (typeof x === 'string')
return Number(x);
else
return String(x);
}
let number3 = flipper(3); // string
let string3 = flipper("3"); // number
@yanickrochon
Copy link

It would be nice to hae this feature working without hacking the class prototype....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment