Categories
JavaScript React

How to Add Browser Notifications to Your React App

With the HTML5 Notification API, browsers can display native popup notifications to users. With notifications, you can display text and icons, and also play sound with them. The full list of options is located at https://developer.mozilla.org/en-US/docs/Web/API/notification. Users have to grant permission to display notifications when they visit a web app to see browser notifications.

Developers have done the hard work for us if we use React because a React component is created to display browser notifications. The React-Web-Notification package, located at https://www.npmjs.com/package/react-web-notification can let us display popups and handle the events that are associated with display the notifications like when use clicks on the notification or handle cases when permissions or granted or denied for display notifications.

In this article, we will build a password manager that lets you enter, edit and delete passwords to the websites and show notifications whenever these actions are taken. We will use React to build the app.

To start, we will run Create React App to create the app. Run:

npx create-react-app password-manager

to create the app. Next, we add our own libraries, we will use Axios for making HTTP requests to our back end, Formik and Yup for form value handling and form validation respectively, MobX for state management, React Bootstrap for styling, React-Copy-To-Clipboard for letting us copy data to the clipboard, and React Router for routing.

We install them by running:

npm i axios formik mobx mobx-react react-bootstrap react-copy-to-clipboard react-router-fom yup react-web-notifications

With all the libraries installed, we can start building our app. We create all the files in the src folder unless otherwise specified.

First, we replace the existing code in App.css with:

.bg-primary {  
  background-color: #09d3ac !important;  
}

to change the top bar’s background color. Next in App.js , replace the current code with:

import React from "react";  
import { Router, Route } from "react-router-dom";  
import HomePage from "./HomePage";  
import { createBrowserHistory as createHistory } from "history";  
import Navbar from "react-bootstrap/Navbar";  
import Nav from "react-bootstrap/Nav";  
import "./App.css";  
const history = createHistory();

function App({ passwordsStore }) {  
  return (  
    <div className="App">  
      <Router history={history}>  
        <Navbar bg="primary" expand="lg" variant="dark">  
          <Navbar.Brand href="#home">Password Manager</Navbar.Brand>  
          <Navbar.Toggle aria-controls="basic-navbar-nav" />  
          <Navbar.Collapse id="basic-navbar-nav">  
            <Nav className="mr-auto">  
              <Nav.Link href="/" active>Home</Nav.Link>  
            </Nav>  
          </Navbar.Collapse>  
        </Navbar>  
        <Route  
          path="/"  
          exact  
          component={props => (  
            <HomePage {...props} passwordsStore={passwordsStore} />  
          )}  
        />  
      </Router>  
    </div>  
  );  
}export default App;

to add our React Bootstrap top bar and our route to the home page. passwordStore is our MobX store for storing our password list in the front end.

Next create HomePage.css and add:

.home-page {  
  padding: 20px;  
}

to add some padding to our page.

Then create HomePage.js and add:

import React from "react";  
import { useState, useEffect } from "react";  
import Table from "react-bootstrap/Table";  
import ButtonToolbar from "react-bootstrap/ButtonToolbar";  
import Button from "react-bootstrap/Button";  
import Modal from "react-bootstrap/Modal";  
import PasswordForm from "./PasswordForm";  
import "./HomePage.css";  
import { deletePassword, getPasswords } from "./requests";  
import { observer } from "mobx-react";  
import { CopyToClipboard } from "react-copy-to-clipboard";  
import Notification from "react-web-notification";

function HomePage({ passwordsStore }) {  
  const [openAddModal, setOpenAddModal] = useState(false);  
  const [openEditModal, setOpenEditModal] = useState(false);  
  const [initialized, setInitialized] = useState(false);  
  const [selectedPassword, setSelectedPassword] = useState({});  
  const [notificationTitle, setNotificationTitle] = React.useState(""); const openModal = () => {  
    setOpenAddModal(true);  
  }; 

  const closeModal = () => {  
    setOpenAddModal(false);  
    setOpenEditModal(false);  
    getData();  
  }; 

  const cancelAddModal = () => {  
    setOpenAddModal(false);  
  }; 

  const editPassword = contact => {  
    setSelectedPassword(contact);  
    setOpenEditModal(true);  
  }; 

  const cancelEditModal = () => {  
    setOpenEditModal(false);  
  }; 

  const getData = async () => {  
    const response = await getPasswords();  
    passwordsStore.setPasswords(response.data);  
    setInitialized(true);  
  }; 

  const deleteSelectedPassword = async id => {  
    await deletePassword(id);  
    setNotificationTitle("Password deleted");  
    getData();  
  }; 

  useEffect(() => {  
    if (!initialized) {  
      getData();  
    }  
  }); 

  return (  
    <div className="home-page">  
      <h1>Password Manager</h1>  
      <Modal show={openAddModal} onHide={closeModal}>  
        <Modal.Header closeButton>  
          <Modal.Title>Add Password</Modal.Title>  
        </Modal.Header>  
        <Modal.Body>  
          <PasswordForm  
            edit={false}  
            onSave={closeModal.bind(this)}  
            onCancelAdd={cancelAddModal}  
            passwordsStore={passwordsStore}  
          />  
        </Modal.Body>  
      </Modal> <Modal show={openEditModal} onHide={closeModal}>  
        <Modal.Header closeButton>  
          <Modal.Title>Edit Password</Modal.Title>  
        </Modal.Header>  
        <Modal.Body>  
          <PasswordForm  
            edit={true}  
            onSave={closeModal.bind(this)}  
            contact={selectedPassword}  
            onCancelEdit={cancelEditModal}  
            passwordsStore={passwordsStore}  
          />  
        </Modal.Body>  
      </Modal>  
      <ButtonToolbar onClick={openModal}>  
        <Button variant="outline-primary">Add Password</Button>  
      </ButtonToolbar>  
      <br />  
      <div className="table-responsive">  
        <Table striped bordered hover>  
          <thead>  
            <tr>  
              <th>Name</th>  
              <th>URL</th>  
              <th>Username</th>  
              <th>Password</th>  
              <th></th>  
              <th></th>  
              <th></th>  
              <th></th>  
            </tr>  
          </thead>  
          <tbody>  
            {passwordsStore.passwords.map(c => (  
              <tr key={c.id}>  
                <td>{c.name}</td>  
                <td>{c.url}</td>  
                <td>{c.username}</td>  
                <td>******</td>  
                <td>  
                  <CopyToClipboard text={c.username}>  
                    <Button  
                      variant="outline-primary"  
                      onClick={() => setNotificationTitle("Username copied")}  
                    >  
                      Copy Username to Clipboard  
                    </Button>  
                  </CopyToClipboard>  
                </td>  
                <td>  
                  <CopyToClipboard text={c.password}>  
                    <Button  
                      variant="outline-primary"  
                      onClick={() => setNotificationTitle("Password copied")}  
                    >  
                      Copy Password to Clipboard  
                    </Button>  
                  </CopyToClipboard>  
                </td>  
                <td>  
                  <Button  
                    variant="outline-primary"  
                    onClick={editPassword.bind(this, c)}  
                  >  
                    Edit  
                  </Button>  
                </td>  
                <td>  
                  <Button  
                    variant="outline-primary"  
                    onClick={deleteSelectedPassword.bind(this, c.id)}  
                  >  
                    Delete  
                  </Button>  
                </td>  
              </tr>  
            ))}  
          </tbody>  
        </Table>  
      </div> {notificationTitle ? (  
        <Notification  
          title={notificationTitle}  
          options={{  
            icon:  
              "http://mobilusoss.github.io/react-web-notification/example/Notifications_button_24.png"  
          }}  
          onClose={() => setNotificationTitle(undefined)}  
        />  
      ) : null}  
    </div>  
  );  
}  
export default observer(HomePage);

This component is the home page of our app. We have a table to display the list of passwords, a button to add a login and password entry, and buttons in each row of the table to copy username and password, and edit and delete each entry. We have the name, URL, username and password columns. The CopyToClipboard component allows us to copy the data we copy to the text prop of the component. Any component can be inside this component. We have one React Bootstrap modal for add password and another one for edit. PasswordForm is our form for adding the password entries, which we will create later.

We show the notifications whenever a username or password is copied, and when an entry is deleted. We do this by setting the notification title with the setNotificationTitle function. We add an onClose handler in the Notification component so that the notification will display again once it is closed.

We have the openModal , closeModal , cancelAddModal , and cancelEditModal functions to open and close the modals. In the editPassword function, we call the setSelectedPassword function to set the password entry to be edited.

The observer we wrap around the HomePage component is for letting us watch the latest values from passwordsStore.

Next, we modify index.js to have:

import React from "react";  
import ReactDOM from "react-dom";  
import "./index.css";  
import App from "./App";  
import * as serviceWorker from "./serviceWorker";  
import { PasswordsStore } from "./store";  
const passwordsStore = new PasswordsStore();

ReactDOM.render(  
  <App passwordsStore={passwordsStore} />,  
  document.getElementById("root")  
);

// If you want your app to work offline and load faster, you can change  
// unregister() to register() below. Note this comes with some pitfalls.  
// Learn more about service workers: [https://bit.ly/CRA-PWA](https://bit.ly/CRA-PWA)  
serviceWorker.unregister();

We pass in our PasswordStore MobX store here, which will pass it to all the other components.

Next, we create PasswordForm.js and add:

import React from "react";  
import { Formik } from "formik";  
import Form from "react-bootstrap/Form";  
import Col from "react-bootstrap/Col";  
import Button from "react-bootstrap/Button";  
import * as yup from "yup";  
import PropTypes from "prop-types";  
import { addPassword, getPasswords, editPassword } from "./requests";  
import Notification from "react-web-notification";

const schema = yup.object({  
  name: yup.string().required("Name is required"),  
  url: yup  
    .string()  
    .url()  
    .required("URL is required"),  
  username: yup.string().required("Username is required"),  
  password: yup.string().required("Password is required")  
});

function PasswordForm({  
  edit,  
  onSave,  
  contact,  
  onCancelAdd,  
  onCancelEdit,  
  passwordsStore  
}) {  
  const [notificationTitle, setNotificationTitle] = React.useState(""); 
  const handleSubmit = async evt => {  
    const isValid = await schema.validate(evt);  
    if (!isValid) {  
      return;  
    }  
    if (!edit) {  
      await addPassword(evt);  
      setNotificationTitle("Password added");  
    } else {  
      await editPassword(evt);  
      setNotificationTitle("Password edited");  
    }  
    const response = await getPasswords();  
    passwordsStore.setPasswords(response.data);  
    onSave();  
  }; 

  return (  
    <>  
      <Formik  
        validationSchema={schema}  
        onSubmit={handleSubmit}  
        initialValues={contact || {}}  
      >  
        {({  
          handleSubmit,  
          handleChange,  
          handleBlur,  
          values,  
          touched,  
          isInvalid,  
          errors  
        }) => (  
          <Form noValidate onSubmit={handleSubmit}>  
            <Form.Row>  
              <Form.Group as={Col} md="12" controlId="name">  
                <Form.Label>Name</Form.Label>  
                <Form.Control  
                  type="text"  
                  name="name"  
                  placeholder="Name"  
                  value={values.name || ""}  
                  onChange={handleChange}  
                  isInvalid={touched.name && errors.name}  
                />  
                <Form.Control.Feedback type="invalid">  
                  {errors.name}  
                </Form.Control.Feedback>  
              </Form.Group> <Form.Group as={Col} md="12" controlId="url">  
                <Form.Label>URL</Form.Label>  
                <Form.Control  
                  type="text"  
                  name="url"  
                  placeholder="URL"  
                  value={values.url || ""}  
                  onChange={handleChange}  
                  isInvalid={touched.url && errors.url}  
                />  
                <Form.Control.Feedback type="invalid">  
                  {errors.url}  
                </Form.Control.Feedback>  
              </Form.Group> <Form.Group as={Col} md="12" controlId="username">  
                <Form.Label>Username</Form.Label>  
                <Form.Control  
                  type="text"  
                  name="username"  
                  placeholder="Username"  
                  value={values.username || ""}  
                  onChange={handleChange}  
                  isInvalid={touched.username && errors.username}  
                />  
                <Form.Control.Feedback type="invalid">  
                  {errors.username}  
                </Form.Control.Feedback>  
              </Form.Group> <Form.Group as={Col} md="12" controlId="password">  
                <Form.Label>Password</Form.Label>  
                <Form.Control  
                  type="password"  
                  name="password"  
                  placeholder="Password"  
                  value={values.password || ""}  
                  onChange={handleChange}  
                  isInvalid={touched.password && errors.password}  
                />  
                <Form.Control.Feedback type="invalid">  
                  {errors.password}  
                </Form.Control.Feedback>  
              </Form.Group>  
            </Form.Row>  
            <Button type="submit" style={{ marginRight: "10px" }}>  
              Save  
            </Button>  
            <Button type="button" onClick={edit ? onCancelEdit : onCancelAdd}>  
              Cancel  
            </Button>  
          </Form>  
        )}  
      </Formik>  
      {notificationTitle ? (  
        <Notification  
          title={notificationTitle}  
          options={{  
            icon:  
              "http://mobilusoss.github.io/react-web-notification/example/Notifications_button_24.png"  
          }}  
          onClose={() => setNotificationTitle(undefined)}  
        />  
      ) : null}  
    </>  
  );  
}

PasswordForm.propTypes = {  
  edit: PropTypes.bool,  
  onSave: PropTypes.func,  
  onCancelAdd: PropTypes.func,  
  onCancelEdit: PropTypes.func,  
  contact: PropTypes.object,  
  contactsStore: PropTypes.object  
};

export default PasswordForm;

Here, we add our form for letting users enter the username and password of their websites. We use the Yup schema object we created at the top of our code to make sure all fields are entered and check that the URL entered is actually a URL. We use the Formik component to handle the form of input changes and get the latest values.

Once the form is checked to be valid by schema.validate promise to resolve to true , then addPassword or editPassword functions from requests.js , which we will create later will be called depending if the user is adding or editing an entry. Once that succeeds, then the getPasswords from the same file is called, and then setPasswords from passwordsStore is called to store the passwords in the store. Finally, onSave passed in from the props in HomePage component is called to close the modal.

We show the notifications whenever an entry is added or edited, and when an entry is deleted. We do this by setting the notification title with the setNotificationTitle function. We add an onClose handler in the Notification component so that the notification will display again once it is closed.

Next, create requests.js and add:

const APIURL = 'http://localhost:3000';  
const axios = require('axios');

export const getPasswords = () => axios.get(`${APIURL}/passwords`);
export const addPassword = (data) => axios.post(`${APIURL}/passwords`, data);
export const editPassword = (data) => axios.put(`${APIURL}/passwords/${data.id}`, data);
export const deletePassword = (id) => axios.delete(`${APIURL}/passwords/${id}`);

to let us make the requests to our back end to save the password entries.

Then we create our MobX store by creating store.js and add:

import { observable, action, decorate } from "mobx";

class PasswordsStore {  
  passwords = [];
  setPasswords(passwords) {  
    this.passwords = passwords;  
  }  
}

PasswordsStore = decorate(PasswordsStore, {  
  passwords: observable,  
  setPasswords: action  
});

export { PasswordsStore };

We have the passwords field which can be observed for the latest value if we wrap the observer function provided by MobX outside a component. The setPasswords is used to set the latest password entries in the store so that they can be propagated to the components.

Finally, in index.html , we replace the existing code with:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <meta charset="utf-8" />  
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />  
    <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <meta name="theme-color" content="#000000" />  
    <meta  
      name="description"  
      content="Web site created using create-react-app"  
    />  
    <link rel="apple-touch-icon" href="logo192.png" />  
    <!--  
      manifest.json provides metadata used when your web app is installed on a  
      user's mobile device or desktop. See [https://developers.google.com/web/fundamentals/web-app-manifest/](https://developers.google.com/web/fundamentals/web-app-manifest/)  
    -->  
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />  
    <!--  
      Notice the use of %PUBLIC_URL% in the tags above.  
      It will be replaced with the URL of the `public` folder during the build.  
      Only files inside the `public` folder can be referenced from the HTML.Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will  
      work correctly both with client-side routing and a non-root public URL.  
      Learn how to configure a non-root public URL by running `npm run build`.  
    -->  
    <title>Password Manager</title>  
    <link  
      rel="stylesheet"  
      href="[https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css](https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css)"  
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"  
      crossorigin="anonymous"  
    />  
  </head>  
  <body>  
    <noscript>You need to enable JavaScript to run this app.</noscript>  
    <div id="root"></div>  
    <!--  
      This HTML file is a template.  
      If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file.  
      The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`.  
      To create a production bundle, use `npm run build` or `yarn build`.  
    -->  
  </body>  
</html>

to change the title and add the Bootstrap CSS.

Now we can run the app by running set PORT=3001 && react-scripts start on Windows or PORT=3006 react-scripts start on Linux.

To start the back end, we first install the json-server package by running npm i json-server. Then, go to our project folder and run:

json-server --watch db.json

In db.json, change the text to:

{  
  "passwords": [  
  ]  
}

So we have the passwords endpoints defined in the requests.js available.

Categories
JavaScript Vue

How to Make a Vue.js App with Buefy Widget Library

Buefy is a lightweight UI component library for Vue.js. It is based on the Bulma CSS framework, which is a framework similar to Bootstrap and Material Design libraries like Vuetify and Vue Material. It provides components like form inputs, tables, modals, alerts, etc, which are the most common components that Web apps use. The full list of components is located at https://buefy.org/documentation.

In this article, we will build a password manager using Buefy and Vue.js. It is a simple app with inputs for entering name, URL, username, and password. The user can edit or delete any entry they entered.

Getting Started

To start building the app, we run the Vue CLI to scaffold the project. We run npx @vue/cli create password-manager to generate the app. In the wizard, we choose ‘Manually select features’ and select Babel, Vuex, and Vue Router.

Next, we install some libraries that we use. We need Axios for making HTTP requests, the Buefy library, and Vee-Validate for form validation. To install them, we run:

npm i axios buefy vee-validate

Building the App

After installing the libraries, we can start building our app. First, in the components folder, create a file namedPasswordForm.vue and add:

<template>  
  <ValidationObserver ref="observer" v-slot="{ invalid }">  
    <form @submit.prevent="onSubmit" novalidate>  
      <ValidationProvider name="name" rules="required" v-slot="{ errors }">  
        <b-field  
          label="Name"  
          :type="errors.length > 0 ? 'is-danger': '' "  
          :message="errors.length > 0 ? 'Name is required': ''"  
        >  
          <b-input type="text" name="name" v-model="form.name"></b-input>  
        </b-field>  
      </ValidationProvider> <ValidationProvider name="url" rules="required|url" v-slot="{ errors }">  
        <b-field  
          label="URL"  
          :type="errors.length > 0 ? 'is-danger': '' "  
          :message="errors.join('. ')"  
        >  
          <b-input type="text" name="url" v-model="form.url"></b-input>  
        </b-field>  
      </ValidationProvider> <ValidationProvider name="username" rules="required" v-slot="{ errors }">  
        <b-field  
          label="Username"  
          :type="errors.length > 0 ? 'is-danger': '' "  
          :message="errors.length > 0 ? 'Username is required': ''"  
        >  
          <b-input type="text" name="username" v-model="form.username"></b-input>  
        </b-field>  
      </ValidationProvider> <ValidationProvider name="password" rules="required" v-slot="{ errors }">  
        <b-field  
          label="Password"  
          :type="errors.length > 0 ? 'is-danger': '' "  
          :message="errors.length > 0 ? 'Password is required': ''"  
        >  
          <b-input type="password" name="password" v-model="form.password"></b-input>  
        </b-field>  
      </ValidationProvider> 

      <br /> 

      <b-button type="is-primary" native-type="submit" style="margin-right: 10px">Submit</b-button> 

      <b-button type="is-warning" native-type="button" @click="cancel()">Cancel</b-button>  
    </form>  
  </ValidationObserver>  
</template>

<script>  
import { requestsMixin } from "@/mixins/requestsMixin";

export default {  
  name: "PasswordForm",  
  mixins: [requestsMixin],  
  props: {  
    edit: Boolean,  
    password: Object  
  },  
  methods: {  
    async onSubmit() {  
      const isValid = await this.$refs.observer.validate();  
      if (!isValid) {  
        return;  
      }
      if (this.edit) {  
        await this.editPassword(this.form);  
      } 
      else {  
        await this.addPassword(this.form);  
      }  
      const response = await this.getPasswords();  
      this.$store.commit("setPasswords", response.data);  
      this.$emit("saved");  
    },  
    cancel() {  
      this.$emit("cancelled");  
    }  
  },  
  data() {  
    return {  
      form: {}  
    };  
  },  
  watch: {  
    password: {  
      handler(p) {  
        this.form = JSON.parse(JSON.stringify(p || {}));  
      },  
      deep: true,  
      immediate: true  
    }  
  }  
};  
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->  
<style scoped lang="scss">  
</style>

This component has the form for users to enter a password entry. We use the ValidationObserver component to watch for the validity of the form inside the component and ValidationProvider to check for the validation rule of the inputted value of the input inside the component.

Inside the ValidationProvider, we have our Buefy b-field input. We get the errors array from the ValidationProvider ‘s slot and check if any errors exist in the type and message props. The label prop corresponds to the label tag of the input. The b-input is the actual input field. We bind to our form model here.

Below the inputs, we have the b-button components, which are rendered as buttons. We use the native-type prop to specify the type of the button, and the type prop is used for specifying the style of the button.

Once the user clicks Save, the onSubmit function is called. Inside the function, this.$refs.observer.validate(); is called to check for form validity. observer is the ref of the ValidationObserver . The observed form of validity value is here. If it resolves to true , then we call editPassword or addPassword depending if the edit prop is true. These 2 functions are from requestsMixin which we will create later. If that succeeds, then we call getPasswords which is also from the mixin, and then this.$store.commit is called to store the latest password entries in our Vuex store. After that, we emit the saved event to close the modal that the form is in.

Next, we create a mixins folder in the src folder and then create requestsMixin.js in the mixins folder. Then we add:

const APIURL = "http://localhost:3000";  
const axios = require("axios");
export const requestsMixin = {  
  methods: {  
    getPasswords() {  
      return axios.get(`${APIURL}/passwords`);  
    }, 

    addPassword(data) {  
      return axios.post(`${APIURL}/passwords`, data);  
    }, 

    editPassword(data) {  
      return axios.put(`${APIURL}/passwords/${data.id}`, data);  
    }, 

    deletePassword(id) {  
      return axios.delete(`${APIURL}/passwords/${id}`);  
    }  
  }  
};

This adds the code to make requests to the back end to save our password data.

Next in Home.vue, we replace the existing code with:

<template>  
  <div class="page">  
    <h1 class="center">Password Manager</h1>  
    <b-button @click="openAddModal()">Add Password</b-button> <b-table :data="passwords">  
      <template scope="props">  
        <b-table-column field="name" label="Name">{{props.row.name}}</b-table-column>  
        <b-table-column field="url" label="URL">{{props.row.url}}</b-table-column>  
        <b-table-column field="username" label="Username">{{props.row.username}}</b-table-column>  
        <b-table-column field="password" label="Password">******</b-table-column>  
        <b-table-column field="edit" label="Edit">  
          <b-button @click="openEditModal(props.row)">Edit</b-button>  
        </b-table-column>  
        <b-table-column field="delete" label="Delete">  
          <b-button @click="deleteOnePassword(props.row.id)">Delete</b-button>  
        </b-table-column>  
      </template>  
    </b-table> <b-modal :active.sync="showAddModal" :width="500" scroll="keep">  
      <div class="card">  
        <div class="card-content">  
          <h1>Add Password</h1>  
          <PasswordForm @saved="closeModal()" @cancelled="closeModal()" :edit="false"></PasswordForm>  
        </div>  
      </div>  
    </b-modal> <b-modal :active.sync="showEditModal" :width="500" scroll="keep">  
      <div class="card">  
        <div class="card-content">  
          <h1>Edit Password</h1>  
          <PasswordForm  
            @saved="closeModal()"  
            @cancelled="closeModal()"  
            :edit="true"  
            :password="selectedPassword"  
          ></PasswordForm>  
        </div>  
      </div>  
    </b-modal>  
  </div>  
</template>

<script>  
// @ is an alias to /src  
import { requestsMixin } from "@/mixins/requestsMixin";  
import PasswordForm from "@/components/PasswordForm";

export default {  
  name: "home",  
  data() {  
    return {  
      selectedPassword: {},  
      showAddModal: false,  
      showEditModal: false  
    };  
  },  
  components: {  
    PasswordForm  
  },  
  mixins: [requestsMixin],  
  computed: {  
    passwords() {  
      return this.$store.state.passwords;  
    }  
  },  
  beforeMount() {  
    this.getAllPasswords();  
  },  
  methods: {  
    openAddModal() {  
      this.showAddModal = true;  
    },  
    openEditModal(password) {  
      this.showEditModal = true;  
      this.selectedPassword = password;  
    },  
    closeModal() {  
      this.showAddModal = false;  
      this.showEditModal = false;  
      this.selectedPassword = {};  
    },  
    async deleteOnePassword(id) {  
      await this.deletePassword(id);  
      this.getAllPasswords();  
    },  
    async getAllPasswords() {  
      const response = await this.getPasswords();  
      this.$store.commit("setPasswords", response.data);  
    }  
  }  
};  
</script>

We add a table to display the password entries here by using the b-table component, and add the b-table-column column inside the b-table to display custom columns. The b-table component takes a data prop which contains an array of passwords, then the data is exposed for use by the b-table-column components by getting the props from the scoped slot. Then we display the fields, by using the prop.row property. In the last 2 columns, we add 2 buttons to let the user open the edit modal and delete the entry respectively. The entries are loaded when the page loads, by calling getAllPasswords in the beforeMount hook.

This page also has 2 modals, one for the add view and one for editing the entry. In each modal, we nest the PasswordForm component that we created earlier inside. We call the openEditModal to open the edit modal. In the function, we set the selectedPassword field to pass it onto the PasswordForm so that users can edit it and set this.showEditModal to true. The openAddModal function opens the add password modal by changing this.showAddModal to true .

Next in App.vue, we replace the existing code with:

<template>  
  <div>  
    <b-navbar type="is-warning">  
      <template slot="brand">  
        <b-navbar-item tag="router-link" :to="{ path: '/' }">Password Manager</b-navbar-item>  
      </template>  
      <template slot="start">  
        <b-navbar-item :to="{ path: '/' }" :active="path  == '/'">Home</b-navbar-item>  
      </template>  
    </b-navbar>  
    <router-view />  
  </div>  
</template>

<script>  
export default {  
  data() {  
    return {  
      path: this.$route && this.$route.path  
    };  
  },  
  watch: {  
    $route(route) {  
      this.path = route.path;  
    }  
  }  
};  
</script>

<style lang="scss">  
.page {  
  padding: 20px;  
}

button {  
  margin-right: 10px;  
}

.center {  
  text-align: center;  
}

h1 {  
  font-size: 32px !important;  
}  
</style>

This adds the Buefy b-navbar component, which is the top navigation bar component provided by Buefy. The b-navbar contains different slots for adding items to the different parts of the left bar. The brand slot folds the app name of the top left, and the start slot has the links in the top left.

We also have the router-view for showing our routes. In the scripts section, we watch the $route variable to get the current route the user has navigated to set the active prop of the the b-navbar-item , which highlights the link if the user has currently navigated to the page with the URL referenced.

In the styles section, we add some padding to our pages and margin for the buttons, and also center some text and change the heading size.

Next in main.js we replace the existing code with:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import Buefy from "buefy";
import { ValidationProvider, extend, ValidationObserver } from "vee-validate";
import { required } from "vee-validate/dist/rules";
import "buefy/dist/buefy.css";
extend("required", required);
extend("url", {
  validate: value => {
    return /^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$/.test(
      value
    );
  },
  message: "URL is invalid."
});
Vue.use(Buefy);
Vue.component("ValidationProvider", ValidationProvider);
Vue.component("ValidationObserver", ValidationObserver);
Vue.config.productionTip = false;
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

This adds the Buefy library and styles to our app and adds the validation rules that we need. Also, we added the ValidationProvider and ValidationObserver to our app so we can use it in the PasswordForm .

Next in router.js , we replace the existing code with:

import Vue from 'vue'  
import Router from 'vue-router'  
import Home from './views/Home.vue'Vue.use(Router)export default new Router({  
  mode: 'history',  
  base: process.env.BASE_URL,  
  routes: [  
    {  
      path: '/',  
      name: 'home',  
      component: Home  
    }  
  ]  
})

This includes the home page route.

Then in store.js , we replace the existing code with:

import Vue from "vue";  
import Vuex from "vuex";Vue.use(Vuex);export default new Vuex.Store({  
  state: {  
    passwords: []  
  },  
  mutations: {  
    setPasswords(state, payload) {  
      state.passwords = payload;  
    }  
  },  
  actions: {}  
});

This adds our passwords state to the store so we can observe it in the computed block of PasswordForm and HomePage components. We have the setPasswords function to update the passwords state and we use it in the components by call this.$store.commit(“setPasswords”, response.data); like we did in PasswordForm . Also, we imported the Bootstrap CSS in this file to get the styles.

After all the hard work, we can start our app by running npm start.

Fake App Backend

To start the back end, we first install the json-server package by running npm i json-server. Then, go to our project folder and run:

json-server --watch db.json

In db.json, change the text to:

{  
  "passwords": [  
  ]  
}

So we have the passwords endpoints defined in the requests.js available.

Categories
JavaScript JavaScript Basics

How to Identify Falsy Values in JavaScript

The following values are falsy in JavaScript, which means that if they are casted to a boolean value, it will be false.

  • false
  • 0
  • empty string: "" , '' , or ``
  • null
  • undefined
  • NaN — not a number value

If you evaluate them as boolean like so, you get:

Boolean(false); // false
Boolean(0); // false
Boolean(""); // false
Boolean(''); // false
Boolean(``); // false
Boolean(undefined); // false
Boolean(null); // false
Boolean(NaN); // false

as opposed to truthy values like objects, which are anything else but the values above:

Boolean({}) // true
Boolean(true) // true
Boolean([]) // true

You can also use the !! shortcut to cast to Boolean, the right ! cast the variable into a boolean and negate the value, and the left ! negate it back to the actual boolean value.

!!(false); // false
!!(0); // false
!!(""); // false
!!(''); // false
!!(``); // false
!!(undefined); // false
!!(null); // false
!!(NaN); // false

Similarly for truthy values:

!!({}) // true
!!(true) // true
!!(\[\]) // true

With shortcut evaluation, boolean ANDs and ORs are evaluated up to the first truthy value:

const abc = false && "abc"; // false, since false is false and "abc" is true

const def = false || "def"; // true, since false is false and "def" is true

It is always good to check for falsy values like null and undefined to avoid crashes.

Categories
JavaScript

Using the URL Object in JavaScript

Manipulating and extracting parts from a URL is a pain if we have to write all the code ourselves. Fortunately, most browsers have the URL object built into their standard library. Now, we can pass in the URL, as a string, to the URL constructor and create an instance of it. Then, we can use the handy value properties and methods to manipulate and get the parts of a URL that we want.

To create a URL object with the URL constructor, we use the new keyword like in the following code:

new URL('http://medium.com');

In above code, we create an instance of the URL object with an absolute URL. We can also create a URL object by passing-in a relative URL as the first argument and the base URL as the second argument. For example, we can write:

new URL('/@hohanga', 'http://medium.com');

Note that the second argument must be a base URL. This means that it must be a valid URL and not just part of it. It must start with the protocol like http:// or https://. We can also define them in a chain-like in the following code:

const mozillaUrl = 'https://developer.mozilla.org';  
const mozillaDevUrl = new URL("/", mozillaUrl);  
const mozillaUrl2 = new URL(mozillaUrl);  
const docsUrl = new URL('/en-US/docs', mozillaUrl2);  
const urlUrl = new URL('Web/API/URL', docsUrl);

If we call toString() on the URL objects above, we should get something like:

https://developer.mozilla.org
https://developer.mozilla.org/
https://developer.mozilla.org/
https://developer.mozilla.org/en-US/docs
https://developer.mozilla.org/en-US/Web/API/URL

The second argument is an optional argument and it should only be passed in when the first argument is a relative URL. The strings or URL objects that we pass in are converted to USVString objects which correspond to the set of all possible sequences of Unicode scalar values. In our code, we can treat them the same as regular strings. A TypeError will be thrown if both argument are relative URLs or if the base and the relative URL together aren’t valid. We can pass in the URL object directly to the second argument because the toString method of the URL object will convert a URL object into a full URL string before being manipulated in the constructor.

A URL object can have the following properties. This article will have the first half of the list of properties and Part 2 of this article will have the second half.

Hash Property

The hash property has the part of the URL that comes after the pound sign (# ). The string isn’t percent decoded, so special symbols like the following are still encoded. They’re encoding with the following mapping. The characters on the left side are converted to the ones on the right side during encoding:

  • ‘:’%3A
  • ‘/’%2F
  • ‘?’%3F
  • ‘#’%23
  • ‘[‘%5B
  • ‘]’%5D
  • ‘@’%40
  • ‘!’%21
  • ‘$’%24
  • “‘“%27
  • ‘(‘%28
  • ‘)’%29
  • ‘*’%2A
  • ‘+’%2B
  • ‘,’%2C
  • ‘;’%3B
  • ‘=’%3D
  • ‘%’%25
  • ‘ ‘%20 or +

For example, if we have the URL https://example.com#hash . Then we can extract the hash with the hash property as follows:

const exampleUrl = new URL('https://example.com#hash');  
console.log(exampleUrl.hash);

Then we get '#hash' in the console.log statement. The property is a USVString , but it’s converted to a string when we retrieve it like we did above. This is not a read-only property, so we can also assign to it like in the following code:

exampleUrl.hash = '#newHash';

For example, if we have:

const exampleUrl = new URL('https://example.com#hash');  
exampleUrl.hash = '#newHash';  
console.log(exampleUrl.hash);

Then we get https://example.com/#newHash as the new URL when we get it with the href property.

Host Property

The host property of the URL object is a USVString that contains the host name. If a port is included after the : , then we also get the port number along with the host. For example, if we have:

const exampleUrl = new URL('https://example.com:8888');  
console.log(exampleUrl.host);

Then we get example.com:8888 . Like other USVString properties, it’s converted to a string when we retrieve it. This is not a read only property, so we can also assign to it like in the following code:

exampleUrl.host = 'example.com';

We can also set the host property to change the URL structure. For example, if we have:

const exampleUrl = new URL('https://example.com:8888/en-US/docs/Web/API/URL/href/');

exampleUrl as the new URL when we get it with the href property.

Hostname Property

With the hostname property, we can get the host name from the URL as a USVString. It will not include the port even if it’s included in the URL string that we used to construct the URL object. For example, if we have:

const exampleUrl = new URL('https://example.com:8888'));  
console.log(exampleUrl.hostname);

Then we get example.com from the console.log statement. Like other USVString properties, it’s converted to a string when we retrieve it. This is not a read-only property, so we can also assign to it like in the following code:

exampleUrl.hostname = ‘newExample.com’;

Then we get that the new URL is https://newexample.com:8888/ when we get it with the href property.

Href Property

The href property of the URL object is USVString that has the whole URL. For example, if we have:

const exampleUrl = new URL(‘https://example.com:8888/en-US/docs/Web/API/URL/href/');  
console.log(exampleUrl.href);

Then when we run the code above, we get https://example.com:8888/en-US/docs/Web/API/URL/href/ which is what we passed into the URL constructor. We can also set the href property by assigning our own value to it. For example, we can write:

const exampleUrl = new URL('https://example.com:8888/en-US/docs/Web/API/URL/href/');  
exampleUrl.href = 'https://newExample.com';  
console.log(exampleUrl.href);

Origin Property

The origin property is a read-only property that returns a USVString with the Unicode serialization of the origin of the URL. The structure of the origin will depend on the type of URL that’s used to construct the URL object. For http or https URLs, the origin will be the protocol followed by :// , then followed by the domain, then followed by the colon (: ), then followed by the port. The default port will only be omitted, which is 80 for http and 443 for https , if it’s explicitly specified. For file protocol URLs, the value will be browser dependent. For blob: URLs, the origin will be the part following blob: . For example, "blob:http://example.com" will be returned as "http://example.com" . For example, if we have:

const url = new URL("https://example.org:443")  
console.log(url.origin);

Then we get:

https://example.org

If we have an http URL like the following:

const url = new URL("http://example.org:80")  
console.log(url.origin);

Then we get:

http://example.org

If we have a non-default port for http or https URLs, like in the following:

const url = new URL("http://example.org:8888")  
console.log(url.origin);
const url2 = new URL("http://example.org:8888")  
console.log(url.origin);

Then we get http://example.org:8888
and http://example.org:8888 respectively.

If we have a blob URL, like in the following:

const url = new URL("blob:http://example.org:8888")  
console.log(url.origin);

Then we get http://example.org:8888 . And for file URLs like the following:

const url = new URL("file://c:/documents/document.docx")  
console.log(url.origin);

Then we get file:// in Chrome.

Password Property

The password property is a writable property that extracts the password portion of the URL before the domain name. Like the other properties, the string is a USVString . If it’s set without the username property being set first, then assigning to this property will silently fail. For example, if we have:

const url = new URL('https://username:password@example.com');  
console.log(url.password);

Then we get password in the console.log statement above. We can also set the password property to the password of our choice. For example, if we have:

const url = new URL('https://username:password@example.com');  
url.password = 'newPassword'  
console.log(url);

Then we get https://username:newPassword@example.com as the new URL when we get it with the href property.

Pathname Property

The pathname property is a USVString property which has the part following the first slash (/). It’s writable property. For example, we can get the pathname value from the URL in the following code:

const url = new URL('https://example.com/path1/path2');  
console.log(url.pathname);

Then we get /path1/path2 when we run the console.log statement above. We can also set the pathname property to the relative URL of your choice by setting it to the part after the domain. For example, we can write:

const url = new URL('https://example.com/path1/path2');  
url.pathname = '/newpath1/newpath2';  
console.log(url.href);

Then we get https://example.com/newpath1/newpath2 when we run the console.log statement above.

Manipulating and extract parts from a URL is a pain if we have to write all the code to do it ourselves. Fortunately, most browsers have the URL object built in to their standard library. Now we can pass in the URL as a string to the URL constructor and to create an instance of a URL. Then we can use the handy value properties and methods to manipulate and get the parts of a URL that we want.

To create an URL object with the URL constructor, we use the new keyword like in the following code:

new URL('http://medium.com');

To see more ways to create an URL object, see Part 1 for more details.

A URL object can have the following properties. This article will have the second half of the list of properties and Part 1 of this article will have the first half. All string values are stored as USVString. USVString are objects which correspond to the set of all possible sequences of Unicode scalar values. All USVString values are converted to strings before we get them, so we can treat them all like regular strings.

Value Properties

port Property

The port property is a USVString property that has the port number of the URL. For example, if we have:

const url = new URL('https://example.com:8888');  
console.log(url.port);

Then we get 8888 from the console.log statement. We can also set the port to get a new URL with by assigning the port property with a new value. For example, if we have the following code:

const url = new URL('https://example.com:8888');  
url.port = '3333';  
console.log(url.href);

Then we get https://example.com:3333/ from the console.log statement when we run the code above.

protocol Property

With the protocol property, we can get the the protocol portion of the URL as a USVString , which is the very first part of the URL. Example protocols include http: , https: , ftp: , file: , etc. For instance, if we have the URL https://example.com, then https is the protocol portion of the URL. If we have the following code:

const url = new URL('https://example.com:8888');  
console.log(url.protocol);

Then we get https: from the console.log statement in the code above.

For other protocols like ftp , it also works:

const url = new URL('ftp://example.com:8888');  
console.log(url.protocol);

If we run the code above, then we get ftp: from the console.log statement in the code above.

We can also set the protocol property to get a new URL. For example, if we have:

const url = new URL('ftp://example.com:8888');  
url.protocol = 'http://'
console.log(url.href);

Then we get http://example.com:8888/ from the console.log above. It also works if we omit the slashes or omit both the colon and the slashes. For example, if we have:

const url = new URL('ftp://example.com:8888');  
url.protocol = 'http:' 
console.log(url.href);

Then we also get http://example.com:8888/ from the console.log above. Likewise, if we have:

const url = new URL('ftp://example.com:8888');  
url.protocol = 'http'
console.log(url.href);

We get the same thing.

search Property

To get the search string or query string from a URL, we can use the search property. The query string is anything after the ? in a URL. Like all the other properties, this one is also USVString property. Note that this property get the whole query string. If you want the individual keys and values from the query string, then we can use the searchParams property. We can use the search property like the following code:

const url = new URL('http://example.com:8888?key1=value1&key2=value2');  
console.log(url.search);

Then we get back ?key1=value1&key2=value2 from the console.log statement when we run the code above. We can also change the query string of the URL by assigning it a new value. For example, if we have the following code:

const url = new URL('http://example.com:8888?key1=value1&key2=value2');  
url.search = 'newKey1=newValue1&newKey2=newValue2';  
console.log(url.href);

Then we get http://example.com:8888/?newKey1=newValue1&newKey2=newValue2 from the console.log statement when we run the code above.

searchParams Property

The search property only gets us the whole query string. To parse the query string into keys and values, we can use the searchParams property, which will get us a URLSearchParams object which has the list of keys and values listed on the query string. The keys and values will be decoded so that special characters are all intact. This is a read only property so we can’t set the query string directly by assigning a new value to this property. For example, to get the query string as a list of keys and values, we can write the following code:

const url = new URL('http://example.com:8888/?key1=value1&key2=value2');  
console.log(url.searchParams.get('key1'));  
console.log(url.searchParams.get('key2'));

Then we get value1 from the first console.log statement and value2 from the second console.log statement. The URLSearchParams object has a get method to get the value of the given query string key by the key name.

Username Property

We can get and set the username part of the URL with the username property. The username is a URL comes before the password and domain name. For example, if we have the following code:

const url = new URL('http://username:password@example.com');  
console.log(url.username);

Then when we run the code above, we get username from the console.log statement above. Also, we can use it to set the username in a URL. For instance, if we have the following code:

const url = new URL('http://username:password@example.com');  
url.username = 'newUserName';  
console.log(url.href);

Then we get http://newUserName:password@example.com/ from the console.log statement in the code above.

Instance Methods

URL object instances also have 2 methods. It has a toString() and a toJSON() method. The toString() method returns a USVString containing the whole URL. It’s the same as the href property for getting the whole URL, but we can’t use the toString() method to set the whole URL like we do with the href property. For example, if we have:

const url = new URL('http://username:password@example.com');  
console.log(url.toString());

Then we get http://username:password@example.com/ from the console.log statement above.

The toJSON() method returns a JSON serialized version of the URL object. However, in most cases, it’s actually the same as what toString() will return. For example, if we have:

const url = new URL('http://username:password@example.com');  
console.log(url.toJSON());  
console.log(url.toString());  
console.log(url.toJSON() === url.toString());

Then we get:

http://username:password@example.com/
http://username:password@example.com
true

from the console.log statements when the code above is run. Then url.toJSON() and url.toString() calls returned the same output, and it’s confirmed by the comparison statement url.toJSON() === url.toString() , which evaluated to true .

Static Methods

There are 2 static methods in the URL constructor. It has the createObjectURL() method and the revokeObjectURL() method. The createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. A DOMString is a UTF-16 encoded string. Since JavaScript uses UTF-16 strings, DOMStrings are mapped directly to strings. Passing null to a method that accepts a DOMString will convert null to 'null' . The createObbjectURL() method accepts an object, which can be a File, Blob, or MediaSource object to create a URL for.For example, we can call the createObjectURL() method like in the following code:

const objUrl = URL.createObjectURL(new File([""], "filename"));  
console.log(objUrl);

Then we get something like:

blob:https://fiddle.jshell.net/4cfe2ef3-74ea-4145-87a7-0483b117b429

Each time we create an object URL with the createObjectURL() method, we have to release it by calling the revokeObjectURL() method to clear it from memory. However, browser will release object URLs automatically when the document is unloaded, but for the sake for improving performance, we should release it manually. The revokeObjectURL() method takes in an object URL as its argument. For example, if we have the object URL above created, then we can use the revokeObjectURL() method to release the object URL from memory like in the following code:

const objUrl = URL.createObjectURL(new File([""], "filename"));  
console.log(objUrl);  
URL.revokeObjectURL(objUrl);

The revokeObjectURL() method returns undefined .

When any part of the URL has special characters, they’re encoded by the rules found in RFC-3896, which has a long list of rules on how to encode different types of characters. It also includes non-English characters, and the percent encoding standard for encoding URLs. The full list of rules are at https://tools.ietf.org/html/rfc3986.

With the URL object, manipulating and extract parts from a URL is no longer a pain since we don’t have to write all the code to do it ourselves. Most browsers have the URL object built in to their standard library. Now we can pass in the URL as a string to the URL constructor and to create an instance of a URL. Then we can use the handy value properties and methods to manipulate and get the parts of a URL that we want. It can manipulate all parts of the URL except the query string portion, which can be manipulated by parsing it into a URLSeachParams object and then call its methods and set its properties to modify the query string. To toString and toJSON methods both convert a URL object into a full URL string.

Categories
JavaScript TypeScript

Type Inference in TypeScript

Since TypeScript entities have data types associated with them, the TypeScript compiler can guess the type of the data based on the type or value that is assigned to a variable. The automatic association of the type to a variable, function parameter, functions, etc. according to the value of it is called type inference.

Basic Type Inference

TypeScript can infer the data type of a variable as we assign values to them. For example, if we assign a value to a number, then it automatically knows that the value is a number without us telling it explicitly in the code that the variable has the data type number. Likewise, this is true for other primitive types like strings, booleans, Symbols, etc. For example, if we have:

let x = 1;

Then the TypeScript compiler automatically knows that x is a number. It can deal with this kind of straightforward type inference without much trouble.

However, when we assign data that consists of multiple data types, then the TypeScript compiler will have to work harder to identify the type of the variable that we assigned values to it. For example, if we have the following code:

let x = [0, 'a', null];

Then it has to consider the data type of each entry of the array and come up with a data type that matches everything. It considers the candidate types of each array element and then combines them to create a data type for the variable x. In the example above, we have the first array element being a number, then the second one being a string, and the third one being the null type. Since they have nothing in common, the type has to be a union of all the types of the array elements, which are number, string, and null. Wo when we check the type in a text editor that supports TypeScript, we get:

(string | number | null)[]

Since we get 3 different types for the array elements. It only makes sense for it to be a union type of all 3 types. Also, TypeScript can infer that we assigned an array to it, hence we have the [].

When there’s something in common between the types, then TypeScript will try to find the best common type between everything if we have a collection of entities like in an array. However, it isn’t very smart. For example, if we have the following code:

class Animal {  
  name: string = '';  
}

class Bird extends Animal{}

class Cat extends Animal{}

class Chicken extends Animal{}

let x = [new Bird(), new Cat(), new Chicken()];

Then it will infer that x has the type (Bird | Cat | Chicken)[]. It doesn’t recognize that each class has an Animal super-class. This means that we have to specify explicitly what the type is like we do in the code below:

class Animal {  
  name: string = '';  
}

class Bird extends Animal{}

class Cat extends Animal{}

class Chicken extends Animal{}

let x: Animal[] = [new Bird(), new Cat(), new Chicken()];

With the code above, we directed the TypeScript compiler to infer the type of x as Animal[], which is correct since Animal is the super-class of all the other classes defined in the code above.

Contextual Typing

Sometimes, TypeScript is smart enough to infer the type of a parameter of a function if we define functions without specifying the type of the parameter explicitly. It can infer the type of the variable since a value is set in a certain location. For example, if we have:

interface F {  
  (value: number | string | boolean | null | undefined): number;  
}

const fn: F = (value) => {  
  if (typeof value === 'undefined' || value === null) {  
    return 0;  
  }  
  return Number(value);  
}

Then we can see that TypeScript can get the data type of the value parameter automatically since we specified that the value parameter can take on the number, string, boolean, null, or undefined types. We can see that if we pass in anything with the types listed in the F interface, then they’ll be accepted by TypeScript. For example, if we pass in 1 into the fn function we have above, then the TypeScript compiler would accept the code. However, if we pass in an object to it as we do below:

fn({});

Then we get the error from the TypeScript compiler:

Argument of type '{}' is not assignable to parameter of type 'string | number | boolean | null | undefined'.Type '{}' is not assignable to type 'true'.(2345)

As we can see, the TypeScript compiler can check the type of the parameter by just looking at the position of it and then check against the function signature that’s defined in the interface to see if the type if actually valid. We didn’t have to explicitly set the type of the parameter for TypeScript to check the data type. This saves us a lot of work since we can just use the interface for all functions with the same signature. This saves lots of headaches since we don’t have to repeatedly set types for parameters and also type checking is automatically done as long as define the types properly on the interfaces that we defined.

One good feature that TypeScript brings in the checking of data types to see if we have any values that have unexpected data types or content. TypeScript can infer types based on what we assign to variables for basic data like primitive values. If we assign something more complex to a variable, then it often is not smart enough to infer the type of the variable that we assigned values to automatically. In this case, we have to annotate the type of the variable directly.

It can also do contextual typing where the type of the variable is inferred by its position in the code. For example, it can infer the data type of function parameters by the position it is in the function signature if we define the function signature in the interface that we used to type the function variable that we assign to.