chainable विधि
आप एक समारोह के बजाय एक वर्ग का उपयोग कर रहे हैं, तो आप उपयोग कर सकते हैं thisतथ्य यह है कि एक विधि उदाहरण उस पर बुलाया गया था रिटर्न को व्यक्त करने के प्रकार (चेनिंग विधि) ।
बिना 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');
साथ 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');
chainable समारोह
जब एक समारोह chainable है आप एक इंटरफेस के साथ यह लिख सकते हैं:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
गुण / तरीकों के साथ chainable समारोह
एक समारोह के अन्य संपत्तियों या तरीकों नहीं हैं (जैसे jQuery(str)बनाम jQuery.data(el)), तो आपको एक अंतरफलक के रूप समारोह में ही लिख सकते हैं:
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');