TypeScript Defining a hash table of functions

2019-04-24 09:46发布

I'm trying to create a definition file for Handlebars, for use with pre-compiled handlebar scripts. Handlebars will put pre-compiled scripts into a string indexed hash table of functions, but I can't figure out or find how this would be defined.

A hypothetical definition would be:

declare module Handlebars {
    export var templates: { (model:any) => string; }[index: string];
}

but that's not a valid definition. The definition should work for a call like this:

var myHtml = Handlebars.templates["person-template"]({FNmae: "Eric"});

A definition like this is close:

export var templates: { (model:any) => string; }[];

But that's an array with a numeric index, and it's not the same thing, and VS Intellisense just decides that the functions in the array are any.

1条回答
等我变得足够好
2楼-- · 2019-04-24 10:35

What you want to use is an object type with an index signature (see spec section 3.5.3, specifically 3.5.3.3).

declare module Handlebars {
    export var templates: {
        [s: string]: (model: any) => string;
    }
}
查看更多
登录 后发表回答