简体   繁体   中英

How to write an interface for a JSON object that contains an array of specific functions

I would like to create an interface for a JSON object. It has n keys with unknown names and each value is an array of functions with a specific signature.

// 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;
}

My code fails on: this.mapping[endPoint] with

Type '{ [x: string]: IHandler[]; }' is not assignable to type 'IHandler[]'.
Property 'length' is missing in type '{ [x: string]: IHandler[]; }'. 

应该只是:

this.mapping[endPoint] = [handler];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM