问题
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:
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;
}
}
来源:https://stackoverflow.com/questions/12846533/typescript-defining-a-hash-table-of-functions