Chainable módszer
Ha ön használ egy osztály helyett egy funkciót, akkor a thistípus, hogy kifejezze azt a tényt, hogy a módszer visszaadja a példány hívták fel (metódusok) .
Anélkül 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');
a 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 funkció
Ha egy függvény chainable beírhatja azt interfész:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
Chainable funkció tulajdonságokkal / módszerek
Ha egy függvény más tulajdonságokkal vagy módszerek (pl jQuery(str)vs jQuery.data(el)), akkor írja a funkciót is, mint egy interfész:
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');