TypeScript基础入门之高级类型的多态的 this类型

转发 TypeScript基础入门之高级类型的多态的 this类型

高级类型

多态的this类型

多态的this类型表示的是某个包含类或接口的子类型。 这被称做F-bounded多态性。 它能很容易的表现连贯接口间的继承,比如。 在下面的例子里,在每个操作之后都返回this类型:

class Query {
  public whereCon: Array<string> = [];

  public constructor(protected tableName: string = '') { }

  public andWhere(key: string, value: string) {
    this.whereCon.push(`${key}=${value}`);
    return this;
  }

  public orWhere(key: string, value: string) {
    this.whereCon.push(`OR ${key}=${value}`);
    return this;
  }
  
  public inWhere(key: string, value: string) {
    this.whereCon.push(`AND ${key} IN (${value})`);
    return this;
  }

  public getSQL(): string {
    return `SELECT * FROM ${this.tableName} WHERE ${this.whereCon.join(' ')}`;
  }

  // ... 其他的操作
}

let generateSQL = new Query('table_name')
  .andWhere('key1', 'value1')
  .orWhere('key2','value2')
  .inWhere('key3','value3')
  .getSQL();

console.log(generateSQL);


运行后输入结果如下

$ npx ts-node ./src/advanced_types_5.ts
SELECT * FROM table_name WHERE key1=value1 OR key2=value2 AND key3 IN (value3)

这个类当然还是有点缺陷的,但是我们可以看出这个特性的使用方式由于这个类使用了this类型,你可以继承它,新的类可以直接使用之前的方法,不需要做任何的改变。

class TQuery extends Query {
  public constructor(tableName: string = '') {
    super(tableName);
  }

  public getUpdateSql(key: string, value: string) {
    return `UPDATE ${this.tableName} SET ${key}=${value} WHERE ${this.whereCon.join(' ')}`;
  }

  // ... 其他的操作
}

let generateSQL = new TQuery('table_name')
  .andWhere('key1', 'value1')
  .orWhere('key2', 'value2')
  .inWhere('key3', 'value3')
  .getUpdateSql('key4', 'value4');
console.log(generateSQL);

运行后输入结果如下

$ npx ts-node ./src/advanced_types_5.ts
UPDATE table_name SET key4=value4 WHERE key1=value1 OR key2=value2 AND key3 IN (value3)

如果没有this类型,TQuery就不能够在继承Query的同时还保持接口的连贯性。 inWhere将会返回Query,它并没有getUpdateSql方法。 然而,使用this类型,inWhere会返回 this,在这里就是 TQuery。

转载于:https://my.oschina.net/zhangdapeng89/blog/2187553

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值