Checking variable type inside if.bind

Hello. In my project I’m iterating through an array of objects in a template using repeat.for, but the type of displayed value can vary - it can be either string, number or boolean, so I want to either straight up display it (${elem.value}) or use my custom element, which is basically a checkbox. That’s why I wanted to use typeof to check the variable type, but it doesn’t return anything (${typeof(elem.value)} doesn’t display anything so typeof(elem.value) === 'boolean' is always false) or just throws an error (when I’m not using parentheses, like this: typeof elem.value). Of course I can create a method in my view model, like isBoolean(value) and it would work, but it would be basically wrapper for what I wanted to use in my template. If anything, I’d rather use lodash, but it would be an unused import in my .ts file. Is there a more elegant way to achieve what I want? Here’s my code for context.

<div repeat.for="elem of item" class="col-md-12">
  <my-checkbox if.bind="typeof(elem.value) === 'boolean'" checked.bind="elem.value" disabled.bind="true">
  <span else>${elem.value}</span>

Make a Value Converter

class TypeOfValueConverter{
    return typeof x;

Sounds like a great idea, but using your value converter I think I wouldn’t be able to use it to compare it to something (please correct me if I’m wrong). So I came up with something like this:

class IsOfTypeValueConverter {
  toView(value, comparedType) {
    return typeof value === comparedType;

and then I can use it like this: if.bind="elem.value | isOfType:'boolean'".

Thanks for the idea, of course if you think it can be done better, let me know :slight_smile:

1 Like

You can use compose and bind viewmodel to a function… that will return component name to render data with

Just want to point out the reason behind missing typeof is that the expression we use in aurelia view template is NOT real JavaScript expression.

It is handled by aurelia-binding parser which supports a subset of real JavaScript expression, plus special syntax for value converters and binding behaviours (that two are totally not real JavaScript). That’s why | is not treated as bit-wise or, & is not treated as bit-wise and.

1 Like