In the forum and on Discord, I often see people struggle with casting states to the appropriate type for a calculation or comparison (math, date, etc.). This stems from the fact that all states are represented as strings, and any calculation/comparison of a string with a typed value will likely either result in an unexpected error, or just fail silently. Either way, it adds a barrier for new users to not only understand that states are strings, but also how to convert that string into something more useful. datetime
states are particularly annoying, as laid out here and here.
Rather than tackle “typed states” as described in the first thread, with all the challenges therein, I wonder if we can take advantage of the fact that attributes can retain their native type. If we look specifically at helpers such as input_boolean
, input_datetime
, and input_number
, we could add an attribute that’s equal to the state, but with the corresponding type intact - boolean, datetime, and float, respectively. It could be called typed_value
or similar, and be readily available for templates to consume with no additional conversion required. input_datetime
does already have a timestamp
attribute, but even that requires some processing for use with many date/time-related Jinja functions.
Another possibility is to add a property to the state object itself, similar to last_changed/last_updated, that corresponds to the typed state value. That would avoid having it pollute the attribute list and still be available in the state object, but those properties aren’t currently provided by the integration. The main challenge is that it would be up to the integration to provide a typed value and it can’t be reliably derived from the state automatically.
Providing the typed value would be relatively easy for the built-in helpers that have explicit types, and could be expanded to other integrations at the developer’s option. Perhaps without a provided typed state, the attribute or state property just returns the state string by default, ensuring that it at least has a value.
I’ll continue to think about how this might work, but wanted to put it out there to see what others think.