Helpers
Last updated
Was this helpful?
Last updated
Was this helpful?
Helpers in Ember are just functions or classes with a well-defined interface, which means they largely Just Work™ with TypeScript. However, there are a couple things you’ll want to watch out for.
The basic type of a helper function in Ember is:
This represents a function which may have an arbitrarily-long list of positional arguments, which may be followed by a single dictionary-style object containing any named arguments.
There are three important points about this definition:
positional
is an array of unknown
, of unspecified length.
named
is a Record
.
Both arguments are always set, but may be empty.
Let’s walk through each of these.
positional
argumentsThe type is an array of unknown
because we don’t (yet!) have any way to make templates aware of the information in this definition—so users could pass in anything. We can work around this using —TypeScript’s way of using runtime checks to inform the types at runtime.
named
argumentsWe specified the type of named
as a Record<string, unknown>
. Record
is a built-in TypeScript type representing a fairly standard type in JavaScript: an object being used as a simple map of keys to values. Here we set the values to unknown
and the keys to string
, since that accurately represents what callers may actually pass to a helper.
(As with positional
, we specify the type here as unknown
to account for the fact that the template layer isn’t aware of types yet.)
positional
and named
presenceNote that even if the user passes no arguments, both positional
and named
are always present. They will just be empty in that case. For example:
Given those constraints, let’s see what a (very contrived) actual helper might look like in practice. Let’s imagine we want to take a pair of strings and join them with a required separator and optional prefix and postfixes:
The basic type of a class-based helper function in Ember is:
Notice that the signature of compute
is the same as the signature for the function-based helper! This means that everything we said above applies in exactly the same way here. The only differences are that we can have local state and, by extending from Ember’s Helper
class, we can hook into the dependency injection system and use services.
For more details on using decorators, see our . For details on using services, see our .