0
我想爲JSON對象創建一個接口。它有n具有未知名稱的鍵,每個值都是具有特定簽名的函數數組。如何爲包含特定功能數組的JSON對象編寫接口
// CLASSES
class Server {
// Private variables
mapping : IMapping = {}
// Public functions
public use(endPoint = "", handler : IHandler) : void {
// Check if the end point exists in the mapping
if(this.mapping[endPoint] === undefined) {
this.mapping[endPoint] = {
[endPoint] : [handler]
};
} else {
}
}
}
// INTERFACES
interface IMapping
{
[key : string] : IHandler[];
}
interface IHandler {
(req : object, res : object, next : object) : void;
}
我的代碼失敗的:this.mapping[endPoint]
與
Type '{ [x: string]: IHandler[]; }' is not assignable to type 'IHandler[]'.
Property 'length' is missing in type '{ [x: string]: IHandler[]; }'.
感謝您的答覆!在這種情況下,我會這樣糾正它: //檢查映射中是否存在終點。如果沒有,則創建它 if(this.mapping [endPoint] === undefined)this.mapping [endPoint] = []; } //將終點與處理程序關聯起來 this.mapping [endPoint] .push(handler); – Giovarco