Tutorials on Typescript

Learn about Typescript from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How to Handle Mouse Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc. To handle mouse event in React you can use MouseEvent type to declare types on handler event argument: You can specify the element on which an event is being handled. It improves the type-safety and shrinks possible properties and methods to those that apply to a given element.

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $40 per month for unlimited access to over 60+ books, guides and courses!

Learn More

TailwindCSS vs. Bootstrap: A CSS Frameworks Comparison

This article will provide a mildly thorough comparison of TailwindCSS vs. Bootstrap to help you determine the more suitable framework for your web development needs. TailwindCSS: As a utility-first CSS framework, TailwindCSS enables developers to construct custom designs without writing bespoke CSS. It provides low-level utility classes that can be combined to create any design directly in the HTML. Bootstrap: As one of the most widely-used CSS frameworks, Bootstrap offers pre-designed components and a grid system. It is designed to aid developers in rapidly creating responsive and consistent web interfaces.

Mastering React and TypeScript: Unlock Success in the Current Web Development Market

In the dynamically progressing tech industry of today, staying relevant requires developers to be well-versed with the most recent tools and technologies. A combination that's experiencing a surge in popularity and demand is React combined with TypeScript. Any developer aspiring to secure a position in a React-focused role must possess a strong grasp of TypeScript. This article discusses why the integration of React with TypeScript is the current trend and offers insights on how to acquire and excel in this potent duo. The demand for React developers skilled in TypeScript is seeing an upward trend. A large number of job advertisements for React or front-end development positions now necessitate the knowledge of TypeScript. But why is this duo becoming more sought-after in the industry? Let's delve into the technical advantages offered by the amalgamation of React with TypeScript. TypeScript introduces the concept of static typing, facilitating type checking during the compilation phase. This allows the early detection of errors, thereby enhancing code reliability and minimizing bugs. Here's an instance to illustrate the difference between JavaScript and TypeScript in terms of type safety:

Type Safety in TypeScript with tRPC for Enhanced Code Reliability

Type safety is a critical feature of TypeScript that aids in preventing runtime errors and boosting developer productivity. In this article, I will dive into how tRPC, a TypeScript RPC framework known for its type safety, builds upon this feature. I’ll be discussing the fundamental concepts of TypeScript type safety, the advantages of tRPC, and its role in augmenting type safety in projects as well. My goal is to give readers a comprehensive understanding of how tRPC can enhance development workflows and minimize technical debt.

Master Custom React Hooks with TypeScript: An Introductory Guide

Are you an aspiring React developer aiming to boost your skills and learn to use and construct custom React hooks with TypeScript? Your quest ends here! In this introductory guide, we will dive into the dynamic world of React hooks coupled with TypeScript, and how they can prop up your development workflow. We'll dissect the advantages of employing React hooks, the challenges they pose, and how TypeScript can help you overcome these challenges. By the conclusion of this introductory guide, you'll have a robust understanding of custom React hooks and their effective utilization in your projects.

Mastering React and TypeScript Development - Simplified Introduction

Are you a React developer interested in enhancing your skill set with TypeScript? Or perhaps you're a beginner in React and are keen to explore how TypeScript can be utilized for intricate patterns? Fear not! This article is for both beginners and seasoned React developers alike.

Exploring Modern Web Development Stack: Fullstack TypeScript with TailwindCSS and tRPC Using PostgreSQL

This article will dive into a development stack that is gaining traction due to its robustness and adaptability. We'll explore what sets this stack apart from well-established stacks like MEAN and MERN, and why developers should consider its adoption. The cutting-edge stack we're exploring comprises several technologies that, although not entirely new, are combined uniquely to boost development efficiency and code quality. This modern stack includes: This stack facilitates enhanced type safety, seamless management of monorepo structures, shared configurations across packages, and a streamlined frontend setup with Vite, React, and Tailwind. Moreover, this stack enables database migration with raw SQL and access via knex.js , using tRPC as the API layer and Koa as the backend framework.

Master Full Stack Development with tRPC: An Introductory Guide

Welcome to this introductory guide on leveraging tRPC for full-stack development. With TypeScript's increasing popularity, tRPC has surfaced as a modern standard that empowers developers to achieve automatic type safety, an optimized developer experience, and exceptional compatibility with existing JavaScript frameworks. This guide aims to introduce you on integrating tRPC into your web stack and its efficient usage with PostgreSQL's modern features and TailwindCSS. This educational article is specifically designed for individuals who:

Introduction to using PostgreSQL with NodeJS: A Beginner's Guide

Are you ready to dive into the world of powerful database management with PostgreSQL and NodeJS? This guide is designed for beginners who want to understand how to use PostgreSQL in their NodeJS projects. Whether you're new to databases or looking to expand your skills, this tutorial will help you get started with confidence. In this guide, we'll cover: By the end of this tutorial, you'll have a solid foundation for building applications with PostgreSQL and NodeJS. For a more visual representation and in-depth details, you may refer to this video tutorial by me, Kristian Dupont, on \newline’s YouTube channel.

Building a Choropleth Map with D3 and Svelte

In this article, we will create a data visualization that displays the ratio of Dunkin’ Donuts locations to Starbucks locations (by state) using D3 and Svelte. Which of America’s largest coffee chains keeps your state awake and ready for the 9-5 workday?
Thumbnail Image of Tutorial Building a Choropleth Map with D3 and Svelte

Building a Bar Chart Race with D3 and Svelte

In this article, we will create a data visualization that animates the changes in the stargazer counts of popular front-end library/framework GitHub repositories over the past 15 years. Which front-end libraries/frameworks currently dominate the web development landscape? Which front-end libraries/frameworks used to dominate web development landscape?
Thumbnail Image of Tutorial Building a Bar Chart Race with D3 and Svelte

Building a Word Cloud with D3 and Svelte

In this article, we will create a data visualization that displays the frequency of words in the lyrics of a song under the Billboard Hot 100 list, Vampire, by Olivia Rodrigo, using D3 and Svelte. Which words do you think catapult a song to the Billboard Hot 100 list?
Thumbnail Image of Tutorial Building a Word Cloud with D3 and Svelte

Static Site Generation with Next.js and TypeScript (Part V) - Build Time Access Tokens and Exporting Static HTML

Disclaimer - Please read the fourth part of this blog post here before proceeding. It demonstrates how to statically generate pages with dynamic routes using the getStaticPath() function. If you just want to jump straight into this tutorial, then clone the project repository and install the dependencies. In the previous part of this tutorial series, we encountered a big problem: each getStaticProps() and getStaticPath() function required us to obtain an access token before being able to request any data from the Petfinder API. This meant that anytime we built the Next.js application for production, we had to obtain several access tokens for the Petfinder API: If we were to add more statically generated pages to the Next.js application that depend on data from the Petfinder API, then we would continue to accumulate more access tokens that are scattered throughout the Next.js application.
Thumbnail Image of Tutorial Static Site Generation with Next.js and TypeScript (Part V) - Build Time Access Tokens and Exporting Static HTML

Static Site Generation with Next.js and TypeScript (Part IV) - Dynamic Routes with getStaticPaths

Disclaimer - Please read the third part of this blog post here before proceeding. It walks through image optimization in a Next.js application with the component of next/image and Blurhash, an algorithm that generates beautiful, lightweight, canvas-based placeholder images. If you just want to jump straight into this tutorial, then clone the project repository and install the dependencies. When you look at client-side routing solutions for single-page applications, such as React Router for React-based applications, you will find that they require you to define each route and manually map each one to a specific page component. With Next.js, you have a file-system based router that automatically maps each page component within the pages directory to a unique route. No extra code or routing library is needed. The route of a page is determined by the location of its page component within the pages directory. For example, if the page component is defined within the file pages/blog/index.tsx (or pages/blog.tsx ), then you can access it at the route /blog .
Thumbnail Image of Tutorial Static Site Generation with Next.js and TypeScript (Part IV) - Dynamic Routes with getStaticPaths

Static Site Generation with Next.js and TypeScript (Part VI) - Client-Side Rendering

Disclaimer - Please read the fifth part of this blog post here before proceeding. It covers how to efficiently build a Next.js application with a single access token that can be used across all getStaticProps() and getStaticPath() functions. It also covers how to export a Next.js application to static HTML. If you just want to jump straight into this tutorial, then clone the project repository and install the dependencies. If all rendering happened on the client-side, then you end up with several problems. For example, suppose you build an application with Create React App . If you disable JavaScript in the browser and reload the application, then you will find the page void of content since React cannot run without JavaScript. Therefore, checking the DOM in the developer console, the
element, where React renders all of the dynamic content, will be shown to be empty. There's also the possibility of the client running on an underpowered device, so rendering might take longer than expected. Or worse, the client has a poor network connection, so the application might have to wait longer for JavaScript bundles and other assets to be fully fetched before being able to render anything to the page. This is why it's important to not blindly render all content with only one rendering strategy. Rather, you should consider taking a hybrid approach when building an application. By having some content pre-rendered in advance via static-site generation (or server-side rendering) and having the remaining content rendered via client-side rendering, you can simultaneously deliver both a highly performant page and an enriching user experience.
Thumbnail Image of Tutorial Static Site Generation with Next.js and TypeScript (Part VI) - Client-Side Rendering

Static Site Generation with Next.js and TypeScript (Part III) - Optimizing Image Loading with Plaiceholder and BlurHash

Disclaimer - Please read the second part of this blog post here before proceeding. It explains the different data-fetching techniques that Next.js supports, and it guides you through the process of statically rendering a Next.js application page that fetches data at build time via the getStaticProps function. If you just want to jump straight into this tutorial, then clone the project repository and install the dependencies. Slow page loading times hurt the user experience. Anytime a user waits longer than a few seconds for a page's content to appear, they usually lose their patience and close out the page in frustration. A significant contributor to slow page loading times is image sizes. The larger an image is, the longer it takes the browser to download and render it to the page. One way to improve the perceived load time of images (and by extension, page) is to initially show a placeholder image to the user. This image should occupy the same space as the intended image to prevent cumulative layout shifting . Additionally, compared to the intended image, this image should be much smaller in size (at most, several KBs) so that it loads instantaneously (within the window of the page's first contentful paint). The placeholder image can be as simple as a single, solid color (e.g., Google Images or Medium) or as advanced as a blurred representation of the image (e.g., Unsplash).
Thumbnail Image of Tutorial Static Site Generation with Next.js and TypeScript (Part III) - Optimizing Image Loading with Plaiceholder and BlurHash

Static Site Generation with Next.js and TypeScript (Part I) - Project Overview

Many of today's most popular web applications, such as G-Mail and Netflix, are single-page applications (SPAs). Single-page applications deliver highly engaging and exceptional user experiences by dynamically rendering content without fully reloading whole pages. However, because single-page applications generate content via client-side rendering, the content might not be completely rendered by the time a search engine (or bot) finishes crawling and indexing the page. When it reaches your application, a search engine will read the empty HTML shell (e.g., the HTML contains a
in React) that most single-page applications start off with. For a smaller, client-side rendered application with fewer and smaller assets and data requirements, the application might have all the content rendered just in time for a search engine to crawl and index it. On the other hand, for a larger, client-side rendered application with many and larger assets and data requirements, the application needs a lot more time to download (and parse) all of these assets and fetch data from multiple API endpoints before rendering the content to the HTML shell. By then, the search engine might have already processed the page, regardless of the content's rendering status, and moved on to the next page. For sites that depend on being ranked at the top of a search engine's search results, such as news/media/blogging sites, the performance penalties and slower first contentful paint of client-side rendering may lower a site's ranking. This results in less traffic and business.
Thumbnail Image of Tutorial Static Site Generation with Next.js and TypeScript (Part I) - Project Overview

How to Use Thunks with Redux Toolkit and TypeScript

Last time we used Redux Toolkit to create a todo app. Since RTK is considered to be the standard way to write redux applications, we will use thunks with Redux Toolkit to write asynchronous logic as well. Thunks are a way to manage side effects when working with Redux. For instance, when we want to fetch some data from a server we need to perform an HTTP request. That request is a side effect because it interacts with the “outer world”. Redux itself doesn't know anything about side effects in an app. All the work is done in the redux-thunk middleware. It extends the store's abilities and lets you write async logic that interacts with the store.
Thumbnail Image of Tutorial How to Use Thunks with Redux Toolkit and TypeScript

How to Use Redux Toolkit with TypeScript

The Redux Toolkit package is intended to be the standard way to write Redux logic. It simplifies the store creation and decreases the amount of boilerplate code. Let's rewrite the application we wrote in one of the earlier posts from scratch to see what will change. First of all, we need to create a new app. We can use Create React App with TypeScript template and then add Redux Toolkit or we can use a template that already includes everything we need.

What Happened to the FC Type's Implicit children Prop in @types/react v18?

In @types/react v18, the implicit children prop was removed from the FC type. According to a pull request for @types/react , this prop was supposed to be removed in @types/react v17, but was postponed to @types/react v18 so that developers can easily upgrade their React applications to v17 with few to zero problems . Assuming React v18 and @types/react v18 are both installed within a React project, and given the following code for a component that accept children as a prop... TypeScript raises the following error:
Thumbnail Image of Tutorial What Happened to the FC Type's Implicit children Prop in @types/react v18?

Find and RegExp Match - How to Fix Object is possibly 'undefined' and Object is possibly 'null' Errors in TypeScript

Consider the following TypeScript code snippet: Let's assume that the list of cars is fetched from a remote API service. In this TypeScript code snippet, we... However, there are two problems with this TypeScript code snippet:
Thumbnail Image of Tutorial Find and RegExp Match - How to Fix Object is possibly 'undefined' and Object is possibly 'null' Errors in TypeScript

Fullstack React with TypeScript Masterclass is LIVE 🎉

The Fullstack React with TypeScript Masterclass is now live! 🎉   This Masterclass teaches you practical React and TypeScript for developing apps from idea to completion, along with all the important tools in the React ecosystem. It expands on the material taught in our comprehensive book,  Fullstack React with TypeScript , and gives you over 10 hours of video lessons taught by Maksim Ivanov. By the end of the first module, you'll already have created your environment for React with TypeScript, and you will have completed basic tasks with TypeScript. The subsequent modules then continue your journey through building multiple apps and learning techniques including:
Thumbnail Image of Tutorial Fullstack React with TypeScript Masterclass is LIVE 🎉

Optimistic UIs with React, Apollo Client and TypeScript (Part III) - Handling Errors

Disclaimer - Please read the second part of this blog post here before proceeding. It walks through the steps taken to update a UI optimistically with Apollo Client. However, it does not discuss how to elegantly handle failed mutations, which, by default, automatically undo optimistic updates made to the UI. If sending a message within a messages client causes the UI to update optimistically with this message, then anytime the server encounters an error (e.g., network or GraphQL) while performing the mutation, the message instantly disappears from the UI. For the user to resend the message, they must retype the message in the input field and resend it. Another problem that arises from reverting the optimistic UI update is the loss of the original timestamp the message was sent at since Apollo Client automatically removes the optimistic data from the cache.
Thumbnail Image of Tutorial Optimistic UIs with React, Apollo Client and TypeScript (Part III) - Handling Errors

Optimistic UIs with React, Apollo Client and TypeScript (Part II) - Optimistic Mutation Results

Disclaimer - Please read the first part of this blog post here before proceeding. It walks through the initial steps of building a messages client that fetches messages from a GraphQL API server. If you are already familiar with the basics of Apollo Client, and only want to know how to update a UI optimistically (for mutation results), then download the project from the part-1 branch of the GitHub repository here and follow the directions in the README.md file to set up the project. In the second part of this tutorial series, we will implement the remaining functionality of the messages client: By the end of this tutorial, you will have recreated the optimistic UI found in Messages :
Thumbnail Image of Tutorial Optimistic UIs with React, Apollo Client and TypeScript (Part II) - Optimistic Mutation Results

Optimistic UIs with React, Apollo Client and TypeScript (Part I) - Project Overview

Liking a tweet on Twitter. Marking an e-mail as read in your G-Mail inbox. These type of simple, low-stake actions seem to happen so quickly that you can perform one action after another without having to wait for the previous to finish resolving. As the defining trait of optimistic UIs , these actions give the feeling of a highly responsive and instant UI. Psychologically speaking, they trick the user into thinking that an action has completed even though the network request it sends to the server has not been fully processed. Take, for example, the like button of a tweet. You can scroll through an entire feed and like every single tweet with zero delays between successive tweets. To observe this, open up a Twitter feed and your browser's developer console. Within the developer console, switch to the network tab and select the "Slow 3G" option under the throttling dropdown to simulate slow 3G network speeds. Slowing down network speeds lets us see the UI updates happen before the server returns a response for the action. Then, filter for network requests sent to a GraphQL API endpoint containing the text "FavoriteTweet" (in the request URL), which tells the server to mark the tweet as liked by the current user. When you click on a tweet's like button, the heart icon disappears, the like count increments by one and the text color changes to pink despite the network request still pending. While the server handles this request, the updates to the UI give the illusion that the server already finished processing the request and returned a successful response.
Thumbnail Image of Tutorial Optimistic UIs with React, Apollo Client and TypeScript (Part I) - Project Overview