eta-dev / eta

Embedded JS template engine for Node, Deno, and the browser. Lighweight, fast, and pluggable. Written in TypeScript
https://eta.js.org
MIT License
1.35k stars 60 forks source link

Adjust type for render functions #277

Closed ninanator closed 3 months ago

ninanator commented 3 months ago

Is your feature request related to a problem? Please describe.

When I use render, I have to write functions wrapping render to ensure that callers are putting in all of the expected fields for the templates. It would be helpful if the render* functions could be typed like:

export function render<T extends Record<string, any>>( // <- this could also be `T extends object` to retain the original typing
  this: Eta,
  template: string | TemplateFunction, // template name or template function
  data: T,
  meta?: { filepath: string }
):

so that, if desired, developers can either define the shape or fall back to Record<string, any>.

Describe the solution you'd like

I'd love to be able to define the render function like:

  const render = eta.render<MyType>('./template.eta', {
    ...fields for MyType...
  });

and if the types do not match, allow the compiler to yell at you. The developer would still be in charge of making sure their types and the templates match, but this would go a long way in helping ensure that any template changes are propagated appropriately across all usages in a project.

I'm willing to open a PR. Thank you!

nebrelbug commented 3 months ago

@ninanator thanks for the suggestion! I agree this would be helpful and will merge if you can open a PR. I think T extends object will likely be best so as not to break typing.

ninanator commented 3 months ago

Completed by https://github.com/eta-dev/eta/pull/278