Hey everyone! As you’ve may noticed, TypeScript 2.7 was released not long time ago and it brings a lot of new features to the table.

In this article we will focus primarily on Unique Symbol Types support, in particular within ES2015 classes, which are also a primary building block for WebComponents.

For our demonstration purpose, we will implement a simple WebComponent for showing/hiding projected content, with following features:

custom element name: my-toggleable

it is both stateful and controllable component

public API contains 2 props: title and show and 1 default content projection via slot .

and and 1 default content projection via . title is gonna render within shadow-dom

is gonna render within shadow-dom show will toggle the content projection visibility from inside the component, or from parent, by setting values to this property ( controlled component pattern )

will toggle the content projection visibility from inside the component, or from parent, by setting values to this property ( controlled component pattern ) on host click, it will toggle visibility of projected content

Usage:

<my-toggleable>

<p>Some text Lorem ipsum dolor sit amet.</p>

</my-toggleable>

Demo:

Demo

Ok lets implement our Toggleable WebComponent:

As we know, standard pattern to implement Custom Element props is following:

internal “private” class property which keeps current property value

getter to that “private” property for public use

setter for “private” property for public use

So let’s say for our title prop, following needs to be implemented

class Toggleable extends HTMLElement {

private _title = 'No title provided'

set title(value: string) {

this._title = value

this.render()

}

get title() {

return this._title

}

}

Because we are using TypeScript, we can annotate our internal property with private accessor.