metoda Chainable
Kiedy używasz klasę zamiast funkcji można użyć thistypu wyrazić fakt, że metoda zwraca instancję Nazwano na (łańcuchowym metod) .
bez 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');
z 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');
funkcja Chainable
Gdy funkcja jest chainable można wpisać go w interfejs:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
Funkcja Chainable o właściwościach / metod
Jeśli funkcja ma inne właściwości lub metody (np jQuery(str)vs jQuery.data(el)), można wpisać samą funkcję jako interfejs:
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');