Skip to content

Typescript types: knownHelpers doesnt allow for custom helpers #1544

@NickCis

Description

@NickCis

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions