TypeScript Defining a hash table of functions

被刻印的时光 ゝ 提交于 2019-12-22 04:25:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!