lit.dev icon indicating copy to clipboard operation
lit.dev copied to clipboard

Add example workaround for conditional attributes when using unsafeStatic

Open jimsimon opened this issue 2 years ago • 3 comments
trafficstars

Trying to use ifDefined inside of unsafeStatic causes a type error from TS and a runtime error from JS: “Cannot convert a Symbol value to a string”. This wasn't immediately apparent to us and, in our case, our editors (Webstorm and VSCode) did not flag the type conversion error from TS at all when the invalid usage is wrapped inside of a <template> element.

The workaround is to use a conditional to determine whether to render the attribute:

import { html, unsafeStatic } from 'lit/static-html';

@property()
type?: string;

render() {
  return html`
    ${unsafeStatic(`
        <input ${this.type ? 'type="${this.type}"' : ''}>some text</input>
    `)}
  `
}

jimsimon avatar Aug 23 '23 22:08 jimsimon

We should fix the original problem: you should be able to use ifDefined in a static template.

justinfagnani avatar Aug 23 '23 22:08 justinfagnani

Wouldn't that require the static unwrapper to lookback and remove the attribute and whole value on nothing?

augustjk avatar Aug 23 '23 22:08 augustjk

Ohhh, right. Sorry I thought it was purely a type issue

justinfagnani avatar Aug 23 '23 23:08 justinfagnani