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。