Polymorphic this Types Keep Chaining Typed

Return this from chainable methods so subclasses keep their own methods available: limit() can precede orderBy() and the types still line up.

TypescriptData Fetching

Code

typescriptsnippet
38 lines
// 多态 this:方法返回 this 而不是具体类名,
// 子类扩展的方法才能继续出现在链式调用的检查里
class Query {
  protected clauses: string[] = [];

  where(condition: string): this {
    this.clauses.push('where ' + condition);
    return this;
  }

  orderBy(field: string): this {
    this.clauses.push('order by ' + field);
    return this;
  }

  build(): string {
    return ['select *', ...this.clauses].join(' ');
  }
}

class PagedQuery extends Query {
  limit(count: number): this {
    this.clauses.push('limit ' + count);
    return this;
  }
}

// limit() 之后仍能调用 orderBy():返回类型随接收者走
const q = new PagedQuery()
  .where('status = active')
  .limit(10)
  .orderBy('created_at');

console.log(q.build());

// 基类实例上没有 limit:链路自然停在基类方法
const base = new Query().where('id = 1');
console.log(base.build());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

select * where status = active limit 10 order by created_at
select * where id = 1

Inside the snippet

Polymorphic this Types Keep Chaining Typed comes down to the classes Query and PagedQuery.

Top-level bindings base hold the demo state — nothing sits inside a function scope.

The result is a fresh construction, so callers can keep their originals.

Core lines

return ['select *', ...this.clauses].join(' ');

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `base`.