Handlebars.js: Typescript types: `knownHelpers` doesnt allow for custom helpers

Created on 28 Aug 2019  ·  4Comments  ·  Source: handlebars-lang/handlebars.js

Before filing issues, please check the following points first:

This will probably help you to get a solution faster.
For bugs, it would be great to have a PR with a failing test-case.


Currently Handlebar's typescript definition don't allow to specify custom helpers on the knownHelper option.

So, to use the knownHelpersOnly option with custom helpers, you have to cast the knownHelpers in order to by pass typescript checks;

function given(...args: any[]): string {
  const options = args.pop();

  if (options.fn) {
    let complete = true;
    const proxy = new Proxy(this, {
      get(context, prop: string): object {
        if (!(prop in context)) {
          complete = false;
        }

        return context[prop];
      },
    });

    const text = options.fn(proxy);

    return complete ? text : '';
  }

  return args.some((a: string): boolean => !a) ? '' : args.join(' ');
}

const templateOptions = {
  helpers: {
    first,
  },
};
const compilerOptions = {
  knownHelpers: { first: true } as unknown, // Without this `unknown` compilation fails
  knownHelpersOnly: true,
};

Hanblebars.compile('My nice template {{first "text"}}', compilerOptions)({}, templateOptions);

The produced error (without using the unknown cast) is the following:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/index.test.ts:93:41 - error TS2345: Argument of type '{ knownHelpers: { first: boolean; }; knownHelpersOnly: boolean; }' is not assignable to parameter of type 'CompileOptions'.
      Types of property 'knownHelpers' are incompatible.
        Type '{ first: boolean; }' has no properties in common with type '{ helperMissing?: boolean; blockHelperMissing?: boolean; each?: boolean; if?: boolean; unless?: boolean; with?: boolean; log?: boolean; lookup?: boolean; }'.

Shouldn't the CompilerOptions have the follow definition?:

interface CompileOptions {
  data?: boolean;
  compat?: boolean;
  knownHelpers?: { [name: string]: boolean };
  knownHelpersOnly?: boolean;
  noEscape?: boolean;
  strict?: boolean;
  assumeObjects?: boolean;
  preventIndent?: boolean;
  ignoreStandalone?: boolean;
  explicitPartialContext?: boolean;
}

(Am I not getting something?. I'm willing to send the PR if this is the right fix)

All 4 comments

Thanks for the offer. I have pushed a slightly different fix. I think in order to get proper auto-completion for the builtin-helpers in IDEs, it is better to keep the builtin names, but still allow any other name.

Thanks for the quick fix! In which version will it be released?

Next patch version. I am thinking what would be a good time to do it. I'm planning Tuesday for the next release.

Released in 4.2.0

Was this page helpful?
0 / 5 - 0 ratings