Learning Typescript with Web Components & Lit

Part 1: Properties, Values, & Data BindingIn my 3-part series on Getting Started with Web components & Lit, we created a sample application to show how custom web components work. In this spin-off, we’ll use these components as containers to de…


This content originally appeared on Level Up Coding - Medium and was authored by David Bethune

Part 1: Properties, Values, & Data Binding

In my 3-part series on Getting Started with Web components & Lit, we created a sample application to show how custom web components work. In this spin-off, we’ll use these components as containers to demonstrate some of the basics of web application development with Typescript.

Quick Index
Part 1: Properties, Values, & Data Binding
Part 2: Working with Arrays
Part 3: Working with JSON Objects

Typescript is the future version of JavaScript, originally sponsored by Microsoft.

Why Learn Typescript?

Typescript is nothing more than the next version of JavaScript, the world’s most popular and important programming language. You can enjoy its futuristic features today by using a server and builder that support Typescript. Add an IDE with Typescript support and you’re ready to blast off!

Today, I recommend Lit for building custom web components with minimum overhead. My Hexxed game uses TS and Lit to render giant animals, buttons with reactive icons, and color palettes that respond to the user.

Why learn TS with Web Components and Lit?

Since the DOM (which the browser actually renders) is ugly and horrible to use, many JavaScript programming examples try to avoid using it altogether! Instead, they will ask you to use “coding playgrounds” where they have setup a web interface to display the output of your code. The alternative is console.log() statements that don’t even display inside your HTML page but outside it in a debugging panel. Yuck.

Without some HTML to display our Typescript results, we are left with the ugly console.log() on the right.

If, however, we were to start out Typescript learning journey with web components already setup, we could go directly from coding Typescript to seeing its real output in the browser. If we are developing any kind of application with a web UI, we can scaffold our component behavior and appearance with Typescript.

Prerequisites: VSCode, Lit, & Vite

If you’re starting the series here, you’ll need VSCode with Lit and Vite installed. You can find step-by-step instructions for these in Part 2 of my web components series, or you can download my Lit starter kit from GitHub which is ready to use out-of-the-box.

Using Values in Your Component

At the end of Part 3 of the previous series, we built a web component that performed routing. The result was to show two different pages of content based on the user’s URL. Let’s look at how that was achieved:

This component uses a JSON object and a property in order to render() a dynamic value in the HTML output.

Assigning a Constant Value

To store the content for our HTML pages, we used a Typescript constant, written const. By definition, a constant is a variable which should not vary! In other words, we define a constant if we don’t expect or want its value to change during our application.

A constant definition starts with const, then its name. The grey-shaded area is a VSCode suggestion for the Typescript type that this constant represents. Much more on that in a later chapter!

Our const definition for Pages also assigns a value (after the = sign). The curly braces around the value tell us that it’s a JSON object.

“Isn’t everything an object?” — “Yes, but that’s not important right now.”

Everything’s an Object

You may have heard that in JavaScript, everything’s an object. And that’s true, but not important right now. For our purposes, I’m going to use the term JSON object so we know we are talking about data in JSON format in our model. JSON (pronounced “JAY-sun”) is the standard way that all data (and everything else) is represented “under the hood” in JavaScript, and therefore in Typescript, too.

JSON isn’t terrible to read once you know the rules.

The yellow text here is the two keys. They must end with a colon. The values here are in blue and must be separated with a comma.

A JSON object can be thought of as a kind of dictionary. Each entry in the dictionary has a key and a value. While we can lookup anything in the dictionary by its key, the items aren’t in any particular order. Each key must be unique and we need the exact key to get the value.

Data binding in Typescript is like Genie. We’ve come a long way since 1965 when this show aired.

Outputting Data with ${expression}

If the page content is stored in our JSON model, we need a way to display it when the component renders (in the render() function’s return).

We can write any valid Typescript expression in the $ curly braces, including function calls or values from our model, like Pages here.

To output data from our model, we use the ${expression} syntax, where expression is a something from our model (including function calls for our functions).

Getting Values Out of JSON

To lookup something in a JSON object, we use an accessor. There are two kinds. Let’s look at the one in this code first.

Pages is a reference to the constant we defined. The value in [square brackets] is the key we want to access from Pages.

The Square Brackets Accessor

Here, we are passing the key we want inside square brackets. This method of accessing a JSON object is particularly useful if we don’t know the key when we write the code, as is the case here. Another way of saying this is that the key is variable. In this case, it comes from a property, which we’ll look at momentarily.

Square Brackets with Literals

Supplying the key as a literal will always result in the same page.

If we knew the key up front, we could pass a literal value in quotes. For example, if always wanted the welcome page and not any other, we can just write “welcome” in quotes.

Note that in Typescript it does not matter which of the three types of quotes you use, as long as each type is property nested. However, the special backtick quote (used here after html to surround the HTML content) has the magical feature of understanding the ${expression} syntax.

Shortcut Accessor for Literals

When we do know the key, there’s an even shorter way to write it. With a dot.

An object with a dot after it is an accessor for the key after the dot.
In a famous episode of I Love Lucy, Fred proudly bakes a cake “seven layers deep.”

In fact, we’ve been using this technique all along without even knowing it. Every time we write object.key in Typescript (and that’s a lot), we are just using this shortcut on some JSON object. We’ve even seen this go “three layers deep” with document.location.pathname in our <dta-home> component.

Here, location is a key off of the document object. And pathname is a key off of the location key!

JSON objects can, and often do, contain other JSON objects in their values. When this happens, we can use this shortcut notation to “drill down” through the keys to get to the value we want. In this example, the JSON object called document has a location key. The value of that key is another JSON object, and it has a key named pathname.

You’ve heard of the Property Brothers? In JS, properties and attributes are brothers. They also need to be identical twins in order to get any work done!

Introducing Properties

This is all well and good for unchanging, static values like our page content. But to give our component dynamic behavior, we need properties. A property is a special kind of variable with two unique features.

  1. It can be set from the outside, via an attribute on your custom element.
  2. Lit will redraw your component if a displayed property changes.

In order to bring in data from the outside, we need a property. In this case, the data we want from the outside is the key of the page we’re supposed to display. These kind of properties are often called public to indicate that they can be affected by outside code. It’s good programming practice to put all of those definitions together — before the render() output. So I’ll add a section for that and a comment in my code:

Your public properties should come after your CSS and before your render() output.

This property definition says that the value of this.page in our model will always be equal to what was passed in from the outside when we use this component in some other HTML. So let’s do it!

Setting Properties with an Attribute

To set the value of a property, we provide an attribute on “the other side” where we call (or use, or invoke) the component. In this design, that’s <dta-home>, because it contains a <dta-page> element that we can put an attribute on.

In <dta-home>, we pass the value of the page= attribute that we want.

In fact, this method of setting properties with attributes is the primary way your web components will communicate with each other. This way, each component only gets the information that it needs, and in a convenient form for you to pass.

You may be wondering at this point, “If we’re setting properties, why are we calling them attributes?” And the answer is that attribute here specifically means propertyName=”value” on an HTML element. That element itself has other properties, hence the separate name. In this text, I’ll use the term page= attribute when I mean the “sent” value — and page property when I mean the “received value” in the other component. Sound good?

Dealing with Default Values

In web applications, it’s often necessary to deal with default or missing values. Even in this very simple app, we only defined two web “pages.” We never said what would happen if the user didn’t navigate to either one! Let’s look at two techniques for dealing with defaults and missing values.

In the page= attribute, we use the “or technique” to deal with a null or empty value.
Not only programming but all logical puzzles, like the famous Lady or the Tiger, can be solved with Boolean operators like AND, OR, and NOT. At the silicon level, chips operate on the same logic in hardware called gates.

Trapping for Null with OR

A great deal of the business logic of computer applications comes down to simple tests of AND and OR. In JS and TS, the OR operator (written || and read “OR”) has a useful feature for dealing with empty values. If the first value is empty, OR returns the second! We can use this to say, “If the pageKey is empty, use ‘welcome’.”

This snippet from W3Schools shows how to write AND and OR in Typescript.

Using OR in the page= attribute results in the default value of ‘welcome’ being passed if the user didn’t type a path on the URL. But what if we didn’t provide a page= attribute at all?

Setting Property Defaults

In <dta-page>, we can set a default value if a property is missing.

Many times in your component definitions, you’ll want to setup defaults for values that you don’t pass at all. This makes it simpler to write your elements, since you only need to pass the attributes that aren’t the defaults.

To achieve this, you can simply assign a value to the property when its defined in the component. Just like our assignment to const earlier, the new value is written after the = sign. In this case, it’s the literal string “welcome”, the key that we want to serve up if we aren’t given one.

Putting It All Together

Ok, then! If we’ve defined the property correctly (in its component definition) and used it correctly (in its caller or parent component), the value from the attribute should be available in the component’s model. Let’s see if it is…

I added a third key with a new HTML value.
Visiting the new URL produces the new page, without any other changes needed.

We’ve Come So Far!

So, fellow travelers, where have we gotten to? We’ve looked at how to define a JSON object that acts like a dictionary and gives back values based on the key we ask for. We’ve seen how attributes and properties combine to pass data from one web component to another. And we’ve shown how using variable data and expressions in your output HTML, together known as data binding, can result in web components that update themselves with minimal effort.

The Atomium in Brussels, Belgium is a piece of sculptural architecture you can walk around in (and I have!). It’s modeled on an iron atom, magnified 165 billion times. What big, exciting things could you build with the small, modular design of web components?

Next Up, The Wonderful World of Arrays

In our next segment, we’ll look at the concept of arrays, the wonderful way that JS deals with lists of things. We’ll create a custom <dta-palette> component that can display color chips for a list of colors we supply. Along the way, we’ll see several great techniques for working with arrays in Typescript.

As always, thank you for reading. See you next time!

— D

Level Up Coding

Thanks for being a part of our community! More content in the Level Up Coding publication.
Follow: Twitter, LinkedIn, Newsletter
Level Up is transforming tech recruiting 👉 Join our talent collective

Learning Typescript with Web Components & Lit was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by David Bethune


Print Share Comment Cite Upload Translate Updates
APA

David Bethune | Sciencx (2022-07-13T01:43:09+00:00) Learning Typescript with Web Components & Lit. Retrieved from https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/

MLA
" » Learning Typescript with Web Components & Lit." David Bethune | Sciencx - Wednesday July 13, 2022, https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/
HARVARD
David Bethune | Sciencx Wednesday July 13, 2022 » Learning Typescript with Web Components & Lit., viewed ,<https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/>
VANCOUVER
David Bethune | Sciencx - » Learning Typescript with Web Components & Lit. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/
CHICAGO
" » Learning Typescript with Web Components & Lit." David Bethune | Sciencx - Accessed . https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/
IEEE
" » Learning Typescript with Web Components & Lit." David Bethune | Sciencx [Online]. Available: https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/. [Accessed: ]
rf:citation
» Learning Typescript with Web Components & Lit | David Bethune | Sciencx | https://www.scien.cx/2022/07/13/learning-typescript-with-web-components-lit/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.