méthode chainable
Lorsque vous utilisez une classe au lieu d'une fonction, vous pouvez utiliser le thisgenre à exprimer le fait qu'une méthode retourne l'instance , il a été appelé (méthodes enchaînant) .
sans this:
class StatusLogger {
log(message: string): StatusLogger { ... }
}
// this works
new ErrorLogger().log('oh no!').log('something broke!').log(':-(');
class PrettyLogger extends StatusLogger {
color(color: string): PrettyLogger { ... }
}
// this works
new PrettyLogger().color('green').log('status: ').log('ok');
// this does not!
new PrettyLogger().log('status: ').color('red').log('failed');
avec this:
class StatusLogger {
log(message: string): this { ... }
}
class PrettyLogger extends StatusLogger {
color(color: string): this { ... }
}
// this works now!
new PrettyLogger().log('status:').color('green').log('works').log('yay');
fonction chainable
Lorsqu'une fonction est chainable vous pouvez taper avec une interface:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
fonction chainable ayant des propriétés / méthodes
Si une fonction possède d' autres propriétés ou méthodes (comme jQuery(str)vs jQuery.data(el), vous pouvez taper la fonction elle - même) comme interface:
interface SayWithVolume {
(message: string): this;
loud(): this;
quiet(): this;
}
const say: SayWithVolume = ((message: string) => { ... }) as SayWithVolume;
say.loud = () => { ... };
say.quiet = () => { ... };
say('hello').quiet()('can you hear me?').loud()('hello from the other side');