2016-11-20 24 views
1

我是爲某些域寫一個特定的內容刮板。因此,對於那些支持我的域只是有一些功能聲明,我們只是說有一個如何確保打字稿模塊符合接口

export function getContent(html: string): string {} 

所以,我有許多文件與例如某個確切的接口...

export interface Domain { 
    supportsHttps: boolean; 
    getContent(html: string): string; 
} 

然後對簡單起見,(使地圖支持的主機名和我的網域文件),我只是

// domainsList.ts 
import * as domainA from './domains/domainA'; 

export default { 
    "www.domainA.com": domainA, 
} 

然後我輸入我的域名列表

// index.ts 
import * as url from 'url'; 
import domains from './domainsList'; 

const maybeDomain: Domain | undefined = domains[url.parse(someUrl).host]; 

if (maybeDomain) { 
    // here I get proper autocompletion ... 
    const content = maybeDomain.getContent(someHtml); 
} else { 
    throw new Error('domain not supported'); 
} 

但是,如果我重新從getContent到getContents的接口中的函數名稱,例如,我實際上沒有任何編譯錯誤從所有域文件內。

我想確保./domains/domainA.ts導出的結構符合我的域接口。我有辦法做到這一點嗎?

回答

0

由於您實際上並沒有定義函數,因此編譯器將不會將它們中的兩個鏈接在一起,因此不會出現錯誤。

此外,接口適合比功能好得多。

您可以通過定義類而不是函數來獲得所有檢查。就像這樣:

class AwesomeDomain implements Domain { 
    public supportsHttps: boolean; 
    getConten(html: string): string { 
     return ''; 
    } 
} 

你可以找到一個完整的例子here

+0

不完全是我想要的,但會使它與一個簡單的對象和接口一起工作,不需要那裏的類。 – Sinewyk