2017-09-24 46 views
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[]; }'. 

回答

0

应该仅仅是:

this.mapping[endPoint] = [handler]; 
+0

感谢您的答复!在这种情况下,我会这样纠正它: //检查映射中是否存在终点。如果没有,则创建它 if(this.mapping [endPoint] === undefined)this.mapping [endPoint] = []; } //将终点与处理程序关联起来 this.mapping [endPoint] .push(handler); – Giovarco

相关问题