refactor: Centralize template render type assertion (#2538)

This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
parent a31816c168
commit 5572ec728e
5 changed files with 44 additions and 16 deletions
@@ -187,15 +187,14 @@ export class ActionsManager implements ActionsExecutor {
triggerData?: TriggerData,
): ActionPrepareCallback {
// Render against the state (incl. HASS) as it is *when the action runs* --
// fixed trigger context, fresh card/HASS state per step. The one cast lives
// here as renderRecursively returns `unknown`.
// fixed trigger context, fresh card/HASS state per step.
return <T>(value: T): T => {
const hass = this._api.getHASSManager().getHASS();
return hass
? (renderer.renderRecursively(hass, value, {
? renderer.renderRecursivelyAsType(hass, value, {
conditionState: this._api.getConditionStateManager().getState(),
triggerData,
}) as T)
})
: value;
};
}
+11
View File
@@ -31,6 +31,17 @@ export class TemplateRenderer {
);
};
// Structure-preserving variant of `renderRecursively`: arrays, records, and
// primitives keep their shape (only string leaves are rendered), so the
// caller's type is asserted back unchanged. Callers whose template renders to
// a *different* type than its input (e.g. a string that yields a boolean)
// must use `renderRecursively` and narrow the `unknown` result at runtime.
public renderRecursivelyAsType = <T>(
hass: HomeAssistant,
data: T,
options?: TemplateRenderOptions,
): T => this.renderRecursively(hass, data, options) as T;
private _generateTemplateContext(
options?: TemplateRenderOptions,
): TemplateContext | undefined {
+7 -3
View File
@@ -136,9 +136,13 @@ export class AdvancedCameraCardElementsCore extends LitElement {
return;
}
const elements = this._templateRenderer.renderRecursively(this.hass, this.elements, {
conditionState: this.conditionStateManager?.getState(),
}) as PictureElements | undefined;
const elements = this._templateRenderer.renderRecursivelyAsType(
this.hass,
this.elements,
{
conditionState: this.conditionStateManager?.getState(),
},
);
// Condition state changes won't change the actual rendered config unless
// `elements` has a template, which is more likely does not. Avoid updating