Latest Tutorials

Learn about the latest technologies 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 Use react-hook-form with TypeScript

React Hook Form is a library that helps you to simplify form validation. It uses React hooks to inject required validation checks and to bind a form and a submit handler. Let's create a signup form with React Hook Form and then type it with TypeScript. Out form will contain 3 fields: To connect the form with validation checks we will use useForm hook from the React Hook Form API: Here, we use register as a value to ref prop on each input. It binds the input with validation. We need to pass the name attribute as well since register relies on it. Also, the name must be unique for register to work properly. The handleSubmit function will call the provided callback if validation is successful. In our case, it will call onSubmit callback and log out all the data from the form. Now let's create a type for form data. Let's call it User : When type is created we can use it to annotate the form data: To make an input required, we can provide register with a settings object. When we specify the required field as true , the validation returns an errors object. We can use this object to access errors on every field in the form: We can also specify a required pattern for each field to perform custom checks:

An elegant guide to Sequelize and Node.js

Sequelize is a promise-based SQL ORM for Node.js, with support to Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL! During this tutorial, we will go through the creation of a simple library database using Sequelize and Node.js system. Models are the soul of Sequelize, we use them to represent the data of our tables, both on a row-level as a model instance, or as a table structure level as a model. Let's create our first model to represent a book in our library. But first using NPM we need to install the following libraries: Let's create a db.js file, to initialize our Sequelize database connection Now, let's create a book.js file to store our model Now let's add an index.js file to serve as our application entry point. Here we will have a main function that we will use to create our first object in the database. Let's have some fun with some crud operations inside our main function. Let's list all the books in our database: Here is the data I got in my DB after running the findAll query: To delete an entry in the database, we use .destroy() method: To update a model we use .update() method: To drop an entire table, we would use the .drop() method: The way we index our data in our database is essential for the functionality of our system, a good index will allow you to properly retrieve data faster, for example, the 2 following queries, gets us the same data The difference is that, since the latter is using the primary Key index, to search for the element will be faster. Models can relate to each other. Let's say we have an author model that relates to the book model where a book could have a single author and an author could have multiple books. Let's create the Author.js file: And we need to update our Book.js file in the following manner to include the authorId foreign key: These are one too many relations. In Sequelize we use the method .belongsTo() and .hasMany() to properly define the relation. In our index.js lets do the following: We've been through a lot within this short post but with these few examples, you should have a good grasp on the core functionalities of Sequelize. Sequelize is a really potent tool for working with SQL databases from within Node.js. If you want to keep going deeper into it, I recommend following it up with learning about Sequelize transactions and migrations. Have fun and keep coding! Check out the documentation of the modules we used in this post: If you have any questions - or want feedback on your post - come join our community Discord . See you there!

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 $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

How to Use Generics in TypeScript

Generics in TypeScript is a way to make your code more abstract and reusable. Let's say you want to create a function that returns a first element from a given list: How to type it? We cannot know beforehand list of what type will be given. We could use overloads to enumerate every possible type we accept: ...Or we could use a union type: ...But all of those ways have a common issue. If we want to pass, for example, an object, we have to define it in the type manually. This isn't convenient, and TypeScript has a better way to do it. Generic type is a type that accepts arguments and uses them in some way. In the case of our head function, we can declare: The angle brackets define a type-parameter . This parameter is used by TypeScript compiler to define the TEntity type later. So, when we use this function like this: ...the TEntity becomes a number . When we use the function like this: ...the TEntity becomes a string . We don't have to manually define a type now, since TypeScript will automatically defer it from the argument. It will even defer a union type for you if pass an array of elements with different types. With generics, you can describe custom types and interfaces in more abstract way. Let's say you want to create a type-alias for array and call it List . You would use this type somehow like this: With TypeScript, you can define a generic type for this: You can read it as a ”type-functionβ€œ. It takes an argument TEntity and returns an array of TEntity . Same with interfaces. You can define an interface with type-parameters to set a type which this interface can work with: Most of the time generic types and interfaces are used to define type-constraints. You can also set constraints for your generic types to make sure it is used properly. Let's say you want your EventHandler to be used only with MouseEvent or KeyboardEvent . Then, you can specify those types as a constraint : You can even define a constraint based on a type-parameter! Let's say you want to create a select function, that returns the value of a property in an object: You don't know beforehand what type of object will be passed to this function. However, you can set a constraint on key argument to ensure selecting only from existing properties on the object : When you use this function with an object: This is also useful when coding in IDE with auto-completion because it will allow you to select a seconds argument: Imagine you need to convert some type in a way to make every field optional. TypeScript already has a Partial utility type . Utility types are generic types that perform some transformation on a given type-parameters. In our case, Partial makes every key in a given object optional. There are many other useful utility types described in the TypeScript documentation .

Thumbnail Image of Tutorial How to Use Generics in TypeScript

How To Port A JavaScript Project To TypeScript

As you might know, TypeScript has picked up huge momentum over the last couple of years, and tons of projects are porting their JavaScript code to TypeScript: In this post, I'll show you how to port existing JavaScript projects to TypeScript. If you don't know TypeScript yet, now is the time to learn it. Below I'll cover: But if you want to learn TypeScript really well, we've got you covered: The Beginner's Guide to TypeScript is available exclusively to newline Pro members. You can join here . TypeScript promises to make JavaScript code more type-safe. This means that functions and variables in your code will not produce errors or bugs due to passing or assigning the wrong type arguments. This is a big deal because type errors are a significant, and frequent, source of bugs in just any codebase . The problem is that JavaScript is dynamically typed, which gives you less support for eliminating type errors. Avoiding type errors in JavaScript requires diligence and rigorous testing. TypeScript helps solve the problem! While testing doesn't go away, it's a massive help to have your editor inform you of any mismatched types as you code. There are a lot of TypeScript boilerplates depending on the type of project you're starting. But what if you already have an existing project and you want to add TypeScript to it? The first step in setting up TypeScript for your project is to create a folder structure with src and dest directories. Here, src is where you will write your TypeScript files. Likewise, dest is where your JavaScript files will be generated once TypeScript compiles your files in the src directory. Note, you can name these two directories anything you want, e.g. built for the dest directory. Next, create a TypeScript configuration file , named tsconfig.json in the root folder in your project. It controls how TypeScript compiles your source files. Here is a basic tsconfig.json file. As you can see, the include section specifies where your source files reside. The outDir specifies where to place compiled files. The target is the JavaScript version you want to target. Now you can compile TypeScript files into JavaScript by running the command tsc in the top level directory in your project. You're now able to write new .ts and .tsx files in your previously JavaScript-only project, but how do you change existing JavaScript files to TypeScript? The good part about TypeScript is that you don't have to! You can keep existing JavaScript files in your source files and only convert them gradually to TypeScript. To convert a JavaScript file into TypeScript, change the file extension from .js or .jsx to the TypeScript equivalent: .ts or .tsx . You might see some errors when TypeScript compiles, because there might be missing types in your new ts files. However, by default, TypeScript will still compile and output the .js files in spite of any errors. To fix errors, add the types where they are missing, e.g : To convert JavaScript functions into TypeScript functions, you must add types to the arguments as well as specify the return type. TypeScript type inference also infers types where possible, meaning that you don't have to explicitly specify all the types in your functions in order to get the file to compile without errors. You'll have to decide the explicitness level you want in your code. Here's a sample JavaScript function we want to convert into TypeScript: Here is how it looks in TypeScript when we add full type annotations to the function. TypeScript is able to infer the return type automatically, so you'll often see the above function typed more simply as follows, using type inference to supply the missing type information: On compilation, this produces exactly the same JavaScript ouput in both cases. Many third-party libraries and NPM packages now supply TypeScript type definitions. These make it possible to use TypeScript type checking and editor autocomplete when you use these libraries. To get these benefits, you must install the type definitions for the package you want to use. Suppose you want to use the react package. You can install its type definitions from NPM by running the command: npm install --save @types/react If you need types for a particular package, check NPM for the type definitions. You might run into problems as you go about porting your JavaScript project to TypeScript. If you want to learn more about working with TypeScript and building apps - for both the browser and Node.js - we have a brand new book for learning TypeScript called The Beginner's Guide to TypeScript and it's available exclusively to newline Pro members . It's written by Christian Santos, a Facebook engineer, who has used TypeScript extensively in his work. If you use Angular or React, both of these frameworks have TypeScript support built in. If you're creating a Node.js project, Microsoft ships a Node.js Starter . If you're creating a library, a package I've used a bunch of times is tsdx which gives you a great zero-config starter for TypeScript package development.

Thumbnail Image of Tutorial How To Port A JavaScript Project To TypeScript

    How to Use useMemo Hook with TypeScript

    The useMemo hook memoizes a function value. It is similar to caching the return value of a function so that the function doesn't get executed if given the same arguments. It helps us to avoid expensive recalculations and speeds up an application. useMemo takes 2 arguments: You don't need any additional typings since TypeScript knows that useMemo accepts a function and an array of dependencies. It is preferable to use eslint-plugin-react-hooks though, to ensure you don't miss any argument in the dependencies array but that's optional. Let's imagine we have a hasher component that takes user keyboard input and hashes it using third-party sha256 hash: The sha256(input) call is pretty expensive and will be called on every render. This can slow down application performance. Let's memoize the hasher! This is not only useful to remember the return value for some arguments, but also to prevent unnecessary component re-renders. For example, when we 2 different inputs in the same component and we don't want changes in one of them to trigger re-rendering in the other.