2015-10-15 32 views
2

我想聲明的打字稿接口,這樣的JSON結構:打字稿強類型的鍵值對申報

{ 
 
404: function() { alert("page not found"); }, 
 
400 : function() {...} 
 
}

關鍵是數量和價值功能,你知道如何在TypeScript中爲這樣的數據約束聲明一個接口?

回答

6

索引

可以使用號碼爲JavaScript的鑰匙,如果你使用[]鍵訪問...

讓我們先從你想要的代碼...

var x = { 
    404: function() { alert("page not found"); }, 
    400 : function() { alert("...");} 
}; 

x.404(); 

上面的最後一條語句(調用404函數)將與Missing ; before statement錯誤,因此你必須使用...

x[404](); 

雖然這仍然將讓你在打字稿(var a = x[404];類型推斷 - a() => void型) - 它不會給你很好的自動完成。

接口這樣的:

interface HttpCodeAlerts { 
    [index: number]:() => void; 
} 

隨着自動完成

通常在JavaScript和打字稿,建議您使用更安全的名稱。簡單地說,你需要以字母開頭他們:

var x = { 
    E_404: function() { alert("page not found"); }, 
    E_400 : function() { alert("...");} 
}; 

x.E_404(); 

接口:

interface HttpCodeAlerts { 
    E_400:() => void; 
    E_404:() => void; 
} 

框架樣式

在大多數語言中,使用了錯誤的更多是這樣的...

class HttpCode { 
    static OK = { responseCode: 200, reasonPhrase: 'Okay' }; 
    static NotFound = { responseCode: 404, reasonPhrase: 'Not Found' }; 
}; 

alert(HttpCode.NotFound.reasonPhrase); 
0

它不是有效的JSON結構,因此無效的JavaScript(都不是TypeScript)。 對象鍵應該是字符串。根據this answer號碼總是轉換爲字符串。

因此,我建議在您的JSON中使用顯式字符串作爲鍵。然後,你可以把它在打字稿喜歡這種模式:

interface ICodes { 
    "404":() => void; 
    [code: string]:() => void; // defines any string key to be function 
} 

var codes: ICodes = { 
    "404": function() { alert("page not found"); }, 
    "400": function() {} 
}; 

// call the function for code 404 
codes["404"](); 
+0

這是無效的JSON,但它是有效的JS。這兩個不完全匹配 – JKillian

2

這或許可以得到答案之一: -

export interface clientSideFunction{ 
    [code: number]:()=>void; 
} 

使用該接口通過將其導入: -

import {clientSideFunction} from 'filePath';