1. 程式人生 > 實用技巧 >校內 第一屆ACM校賽——熱身賽

校內 第一屆ACM校賽——熱身賽

0x01 安裝

00x2 語言核心

0x03 實戰案例

TypeScript的泛型約束

TypeScript的泛型存在和C#的泛型一樣的使用上的不便利,泛型引數在作用域內能夠呼叫的方法一定是要通過泛型引數的約束來指定的,例如一個泛型函式:

function test<T>(){
  let t = new T();           // 構造例項,compiler error!
  let x = t.method();        // 呼叫成員方法,compiler error!
  let x = t.static_method(); // 呼叫靜態方法,compiler error!
}

無論是呼叫方法還是構造T的例項,都不能直接通過,需要給T新增約束來解決對應的問題:

interface Something{
  method():number;  
}

interface SomethingBuilder<T>{
  new(...constructorArgs: any[]): T; 
  static_method():number;
}

// 1. 約束T擴充套件了Something,從而t可以呼叫Something的方法。
// 2. 約束了C擴充套件了構造T的匿名介面,從而constructor: C可以被用來構造T的例項t
// 3. 新增一個新的泛型C,C擴充套件了SomethingBuilder<T>這個構造Something的元介面,同時把構造需要的型別和引數作為test函式的引數傳入
function test<T extends Something, C extends SomethingBuilder<T>>(builder: C, ...args: any[]){
  let t = new builder(args);       // OK
  let x = t.method();            // OK
  let x = builder.static_method(); // OK
}

// 用例:
class Some implements Something{
  constructor(){
   // 
  } 
  static static_method():number{
    return 0;
  }
   
  method():number{
    return 1;
  }
}

test(Some);