TypeScript · Senior · Pytanie 22 z 75
Co daje zwracany typ this w metodzie klasy?
class Query {
where(c: string): this { /* ... */ return this; }
}
class UserQuery extends Query { active(): this { return this; } }
new UserQuery().where('x').active();- ✓Poprawna odpowiedź: Polimorficzne
this: łańcuch metod zachowuje typ podklasy - 2Metoda zawsze zwraca typ klasy bazowej
Query - 3To błąd:
thisnie można używać jako typu
Wyjaśnienie
Gdyby where zwracało Query, po nim .active() byłoby niedostępne. Polimorficzne this jest wygodne dla płynnych API i builderów. Jest też this is T w metodach-type guardach.