метод змеевидных
Когда вы используете класс вместо функции, вы можете использовать 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');
функция змеевидных
Когда функция цепная вы можете ввести его с интерфейсом:
function say(text: string): ChainableType { ... }
interface ChainableType {
(text: string): ChainableType;
}
say('Hello')('World');
Функция змеевидных со свойствами / методов
Если функция имеет другие свойства и методы (например , 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');