DEV Community

Cover image for The Basics you need to know to start with TypeScript
Deepak Yadav
Deepak Yadav

Posted on

The Basics you need to know to start with TypeScript

💻 Intro

TypeScript is a superset of JavaScript and adds optional static typing, classes, interfaces, and other advanced features to the language. It helps to improve the development experience for large-scale JavaScript applications by enabling developers to catch errors at compile-time rather than runtime.

🚀 Why TypeScript is awesome

We often spend hours debugging our code because of silly mistakes like passing the wrong props, typos in variable names, messing with the types, and much more.

Typescript helps us the developer to save time by providing static typing. It allows specifying the types of variables, parameters, props and function return types, which helps to catch errors at compile-time rather than the runtime and definitely helps in reducing the breaking of code in production.

TypeScript could be painful & seems extra work but it is worth the pain & effort !!


🔧 How to use Typescript with React

Using Typescript can be a little tricky sometimes, I have tried to provide examples of typescript with constructs for React application use.

⇒ Variables

Variables can be assigned to the various primitive data types like string, number, boolean, etc. Below is how we add types to variables

var name : string = 'John';
var age : number = 18;  
var isPresent : boolean = true;

Enter fullscreen mode Exit fullscreen mode

⇒ Array

There are a couple of ways to give the type to the array

var nameArray : string[];                 //declaration
nameArray = ["John", "David" , "Tom"];   //initialization
/* Another way of declaring array is 
var nameArray : Array<string>   */

Enter fullscreen mode Exit fullscreen mode

Also, we can give an optional type to the array which can take two or more types in the array.

//Optional type either string or number
let values : (string | number)[]= ['Apple', 2, 'Orange', 3, 4, 'Banana']

Enter fullscreen mode Exit fullscreen mode

⇒Tuple

Tuple is similar to the multi-type array only catch is that we don't have an optional type but a mandatory type which an array will contain.

/* Tuple */
var person : [number, string] = [18, "John"];

/* Tuple Array */
var users : [number, string, string][];
users = [[18, "John", "Admin"],[23, "David", "Accountant"],
[40, "Tom", "Admin"]];

Enter fullscreen mode Exit fullscreen mode

⇒ Types and Interfaces

Types and Interfaces are used to define custom types for variables, functions, and other constructs. Both types and interfaces serve a similar purpose, but they have some key differences.

One of the key differences between types and interfaces is that interfaces can be extended, while types cannot.

Another difference between types and interfaces is that interfaces can define optional and read-only properties, while types cannot.

In general, both improve code readability and maintainability.

⇒Types

Defining custom types with Type

type TagType = {
  id: string;
  label: string;
};
var Tag : TagType = {
    id: "123",
    label: "TypeScript"
  };

// Extending type with another type
type BlogType = {
  title: "string;"
  body: string;
}& TagType;

var Blog : BlogType = {
title: "\"Typescript Fundamentals\","
id: "101",
label: "Typescript",
body: "Things you need to know to start ..."
}

Enter fullscreen mode Exit fullscreen mode

⇒Interfaces

Defining custom types with Interface

interface TagInterface { 
   id: string;
   label: string;
   showTag: ()=>string; 
} 

var Tag : TagInterface = {
    id: "123",
    label: "TypeScript",
    showTag?    : () =>{return "Hi there"} // Optional properties '?'
  };

// Extending interface with another interface
interface BlogInterface extends TagInterface{
  title: "string;"
  body?: string;
};

 var Blog: BlogInterface = {
   title: "\"Typescript Fundamentals\","
   id: "101",
   label: "Typescript",
   showTag: () => {
      return "Hi Tags";
   },
 };

Enter fullscreen mode Exit fullscreen mode

⇒Function

Functions in typescript can have typed parameters, typed return values, and optional parameters. Here's an example

//TagType is defined in the previous examples
const [tags, setTags] = useState<TagType[]>([]);
const addTag = (tag: Tag) => {
   setTags((prev: Tag[]) => [...prev, tag]);
 };

Enter fullscreen mode Exit fullscreen mode

⇒Components

Functional components in TypeScript provide a simple and powerful way to build user interfaces with type safety and code clarity. The React.FC type is used to define the type of functional component. This provides additional type safety by ensuring that the component returns a valid JSX element.

import React, { FC } from "react";
type NewTagProps = {
  onAddTag: (tag: TagType) => void;
  availableTags: TagType[];
};
export const NewTag: FC<NewTagProps> = ({
  onAddTag,
  availableTags,
}) => {
console.log("Availble Tags ",availableTags);
  return (
    <div>
      <h3 className="text-center my-3">New Tags Availble</h3>
      {
        // Map the available tags ${availableTags}
      }
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Typescript Types

Some special TypeScript types that need to be highlighted:

  • any - Type any is a special type
  • As the name presents it represents any type (all kinds of) of value it will help to escape the type checking
  • unknown - Type unknown is the type-safe version of any.
  • void - Type void is the absence of any type.

💡Tips

You would probably be using VS code editor and the best way to get started with typescript is to download a typescript extension which will help you to provide autocomplete suggestions. This will help to get started with ease.

To improve the hands-on experience, one can explore Typescript Playground

Conclusion

TypeScript is a powerful programming language that offers several benefits over JavaScript. With TypeScript, developers can write code that is more reliable, easier to maintain, and more scalable than traditional JavaScript.

TypeScript has gained significant popularity recently and is now widely used in large-scale applications such as Angular, React, and Node.js. By learning TypeScript, developers can improve their skills and stay up-to-date with the latest trends in software development.

Leave a ❤️ if you found this article helpful.

Top comments (1)

Collapse
 
devto2k5 profile image
dev procedure

JavaScript applications by enabling developers to catch errors at compile-time rather than runtime.

But developers are constantly "testing" their lines of code (at runtime) in a JavaScript debugger anyway.

Thus, is adding TypeScript on top of JavaScript really that beneficial in regards to "type checking"? And even so, in a large application?

The more I look at it, TypeScript is just adding another layer of "complexity." and with very little benefit when you see that "catching errors at compile time" is not really a benefit as developers are constantly testing/running their code (at run time) LINE-by-LINE anyway.

Time Saved? No way.