lit.dev
lit.dev copied to clipboard
Add example workaround for conditional attributes when using unsafeStatic
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>
`)}
`
}
We should fix the original problem: you should be able to use ifDefined in a static template.
Wouldn't that require the static unwrapper to lookback and remove the attribute and whole value on nothing?
Ohhh, right. Sorry I thought it was purely a type issue