metoda Chainable
Când utilizați o clasă în locul unei funcții, puteți utiliza thistipul pentru a exprima faptul că o metodă returnează instanță a fost numit pe (înlănțuire metode) .
Fără 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');
cu 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');
funcţia Chainable
Atunci când o funcție este chainable îl puteți introduce cu o interfață:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
Funcția Chainable cu proprietăți / metode
Dacă o funcție are alte proprietăți sau metode (cum ar fi jQuery(str)vs jQuery.data(el)), puteți introduce funcția în sine ca o interfață:
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');