2017-06-14 99 views
2

我有這樣的代碼:DRY與打字稿和構造函數選項對象

export interface LDAPPoolOpts { 
    id: number; 
    size: number; 
    connOpts: any; 
    active: Array<any>; 
    inactive: Array<any>; 
    dn: string; 
    pwd: string; 
    waitingForClient: Array<Function> 
} 


export class Pool { 

    id: number; 
    size: number; 
    connOpts: any; 
    active: Array<any>; 
    inactive: Array<any>; 
    dn: string; 
    pwd: string; 
    waitingForClient: Array<Function>; 

    constructor(opts: LDAPPoolOpts) {} 

} 

,你可以看到構造該類只是需要一個選項與類型的對象:LDAPPoolOpts

我的問題是:如何避免重複自己必須爲類和選項對象接口聲明完全相同的字段?

您不能擴展接口..並且實現接口並不意味着您繼承了接口的字段。

我應該聲明一個類型而不是接口嗎?

回答

3

你是正確的,你不能擴展接口,實現接口要求你再次寫出屬性。儘管這個解決方案改變了你的類的結構,但是一種方法是在類中使用接口類型創建一個屬性。

export interface LDAPPoolOpts { 
    id: number; 
    size: number; 
    connOpts: any; 
    active: Array<any>; 
    inactive: Array<any>; 
    dn: string; 
    pwd: string; 
    waitingForClient: Array<Function> 
} 


export class Pool { 
    opts: LDAPPoolOpts; 

    constructor(opts: LDAPPoolOpts) { 
     this.opts = opts; // assign to the property how you see fit 
    } 
} 
+0

是的,這可能是一個很好的解決方案,將清理一些東西。絕對惱人的是必須在兩個不同的地方保留相同的確切屬性列表。 –

1

我經常使用的是以下幾點:

export class Pool { 
    // ... 

    constructor(initializer?: Partial<Pool>) { 
     if (initializer) { 
      Object.assign(this, initializer) 
     } 
    } 
} 

這當然,假定類具有相同的屬性應該初始化對象,所以這基本上是非常相似的對象初始化在C#中。如果您還將實例成員初始化爲有意義的默認值,則此方法效果最佳。

+0

謝謝,你能解釋一下參數在你的代碼中做了什麼嗎? –

+0

@AlexanderMills'部分'與'Pool'相同,除了每個屬性(包括每個方法)都是可選的。即你可以做'新的Pool({id:1337})'沒有TypeScript拋出關於缺少屬性的錯誤。如果沒有'部分',你必須指定初始化對象中的每個屬性,包括任何methods_。 –