2016-03-05 63 views
1

在Typescript中,我可以用下面的其他接口定義接口函數對象嗎?我正在試圖定義我要在我的Ajax函數中使用的對象。使用類實現定義接口對象

但有了這個代碼,我得到一個錯誤:

Error:(22, 1) TS2346: Supplied parameters do not match any signature of call target.

錯誤設置的實例。

interface IXHR { 
    Ajax(ajax: IAjax): string; 
} 

interface IAjax { 
    method: string; 
    url: string; 
    async: boolean; 
    callback?: (data: string) => void; 
} 

class XHR implements IXHR { 
    public Ajax(ajax: IAjax) { 
     return ajax.url; 
    } 

    constructor() {} 
} 

let instance = new XHR(); 

instance.Ajax('GET', 'URL', true); 
+1

您方法'IXHR'中定義的'Ajax'只有一個參數,而你試圖用3個參數調用它的實例 – yarons

+0

它不能使用IAjax接口嗎?我必須在Ajax函數中寫入所有參數,如下所示:Ajax(method:string,url:string,async:boolean,callback ?:()=> void):string;另一種方式只是看起來更光滑:) – aventic

+0

我會盡力爲你的問題寫一個更完整的答案 – yarons

回答

1

你的方法AjaxIXHR定義有一個參數,而你試圖用3個參數與您的實例調用它。

你的實例調用,如果你想讓它符合你的接口,應該是這樣的:

instance.Ajax({method: 'GET', url: 'URL', async: true}); 

另一種選擇是實現IAjax接口,並使用該實施:

interface IXHR { 
    Ajax(ajax: IAjax): string; 
} 

interface IAjax { 
    method: string; 
    url: string; 
    async: boolean; 
    callback?: (data: string) => void; 
} 

class Ajax implements IAjax { 
    constructor(public method: string, public url: string, public async: boolean, public callback?) { 

    } 
} 

class XHR implements IXHR { 
    public Ajax(ajax: IAjax) { 
     return ajax.url; 
    } 

    constructor() {} 
} 

let instance = new XHR(); 
let iAjax: IAjax = new Ajax('GET', 'URL', true); 
instance.Ajax(iAjax); 
+0

這太好了。感謝您的回答。它只是不像我想象的那麼漂亮。但我的厭惡時刻必須是爭論,我試圖通過3,但從來沒有想到它是一個對象,哈哈! :) – aventic