2015-10-30 73 views
2

我正在爲當前項目編寫一個小型模型系統。我希望圖書館的消費者能夠向API提供他們自己的模型定義。在查詢服務器時,API應輸出用戶模型的實例。在打字稿中創建一個通用工廠(未解決)

// Library Code 
interface InstanceConstructor<T extends BaseModel> { 
    new(): T; 
} 

class Factory<T extends BaseModel> { 
    constructor(private cls: InstanceConstructor<T>) {} 

    get() { 
     return new this.cls(); 
    } 
} 

class BaseModel { 
    refresh() { 
     // Refresh returns a new instance, but it should be of 
     // type Model, not BaseModel. 
    } 
} 

// User Code 
class Model extends BaseModel { 
    // Custom Model 
    do() { 
     return true; 
    } 
} 

我無法弄清楚如何在這裏完成模式。只是讓工廠吐出正確的實例很容易,但/refresh上的BaseModel需要也返回Model,而不是any

更新10/2

(此時在技術上1.8 DEV)試圖打字稿@接下來我似乎能夠得到解決,其中模型可以參考本身(this)發行及類型後系統可以遵循它。然而,我無法

// Library Code 
export interface InstanceConstructor<T extends BaseModel> { 
    new(fac: Factory<T>): T; 
} 

export class Factory<T extends BaseModel> { 
    constructor(private cls: InstanceConstructor<T>) {} 

    get() { 
     return new this.cls(this); 
    } 
} 

export class BaseModel { 
    constructor(private fac: Factory<this>) {} 

    refresh() { 
     // get returns a new instance, but it should be of 
     // type Model, not BaseModel. 
     return this.fac.get(); 
    } 
} 

// User Code, Custom Model 
export class Model extends BaseModel { 
    do() { 
     return true; 
    } 
} 

// Kinda sucks that Factory cannot infer the "Model" type 
let f = new Factory<Model>(Model); 
let a = f.get(); 

let b = a.refresh(); 

我的打字稿跟蹤器在此間開幕的一個問題: https://github.com/Microsoft/TypeScript/issues/5493

更新12/1(未解)

此,根據打字稿問題跟蹤器,是不可能的。 「Polymorphic this」功能僅適用於不包含構造函數的非靜態類成員。

回答

2

你需要使用特殊的this類型:

class BaseModel { 
    refresh(): this { 
     // Refresh returns a new instance, but it should be of 
     // type Model, not BaseModel. 
    } 
} 

在寫作的時候,此功能只適用於每晚構建打字稿npm install [email protected]),並且將在打字稿1.7可用。請參閱https://github.com/Microsoft/TypeScript/pull/4910如果你想跟蹤具體的提交或閱讀更多關於如何this工程

+0

不錯,現在我知道我需要的名字!我會用TS @接下來嘗試一下,謝謝你的提示。 – Xealot