Skip to main content

Command Palette

Search for a command to run...

Typescript Basics: Grasp the Essentials in 10 Minutes

Updated
5 min read
Typescript Basics: Grasp the Essentials in 10 Minutes
S

Hey there, I'm Shiwanshu, a passionate frontend developer and designer hailing from India. With proficiency in NextJS, ReactJS, CSS3, HTML5, Figma, UI Design, and Typescript, I've embarked on a journey into the tech space. This blog is a documentation of my progress as I delve deeper into the world of technology.

TypeScript is a superset of JavaScript that adds type safety and extra features to help with development. If you have used languages like C, C++, or Java, you know that when declaring variables, we add their types, like int num1 = 5. Similarly, TypeScript adds type safety for development purposes only. Note that the browser does not understand TypeScript, so it is only used in your development environment. Today, we will learn the most common concepts you will use when creating a ReactJS project with TypeScript.

Basic Types

There are some types that we can categorize as basic types in TypeScript:

  1. string - A variable of type string.

  2. number - A variable of type number.

  3. boolean - A variable of type boolean.

  4. string[] - An array of strings.

  5. number[] - An array of numbers.

  6. boolean[] - An array of booleans.

Type Annotations

const color:string = 'red';
const num1: number = 8;
const isRed: boolean = true;
const colors:string[] = ['red', 'blue', 'green'];
const numbers:number[] = [1,2,3,4,5];
const isNumEven:boolean[] = [false, true, false, true, false];

The type is declared after the variable name, following a colon. These are called type annotations. For instance, const color:string = 'red'; here, string is the type for the variable color. The variable can only hold values of the declared type. If you try to use a different type, it will throw an error.

Function Type Annotations

function add(number1: number, number2: number): number{
    return number1 + number2;
}

Here, the number after the colon in the parameters are the type annotations we expect them to be.

The number type after the parentheses is the return type for the function add.

Type Inferences

When types are not explicitly given, TypeScript can sometimes guess the type.

const x = 3;
const name = 'Ram Kumar';

In these cases, you don't need to explicitly provide the types. If you hover over the variable names, you will see that it says x is a number and name is a string. TypeScript knows the expected types of these variables based on their initialization.

Similarly, for certain functions, you don't need to provide type annotations.

function getName(){
    return 'Ram Kumar';
}

Interface

We can use the object types to define the structure of a particular object in TypeScript.

function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}

Here, the parameter person is defined, and after the colon, we specify that we expect person to have the following type: the name property should be a string, and the age property should be a number.

Instead of writing the types like this we can also create interface.

interface Person {
  name: string;
  age: number;
}

function greet(person: Person) {
  return "Hello " + person.name;
}

Note that each property inside the interface is followed by a semicolon, unlike in JavaScript where commas are used.

More example:

interface Mouse{
    model: string;
    year: number;
    setYear: (year:number) => void;
    setModel: (model:string) => void;
}

const logitech: Mouse = {
    model: 'Logitech',
    year: 2024,
    setYear (nextYear:number)  {
        this.year = nextYear;
    },
    setModel (nextModel: string){
        this.model = nextModel;
    }
}

console.log(logitech)
logitech.setYear(2025);
console.log(logitech);

Optional Properties:

You can define optional properties by adding ? after the property name and before the colon in object types or interfaces. This means that you may or may not define this property when you are creating an object using this interface as the type annotation.

interface BookType{
    version: number;
    bookBinding: string;
    pages: number;
}

interface Book{
    title: string;
    type?: BookType; // Optional
}

const book:Book = {
    title: 'Atomic Habits'
// You can skip type and it won't throw error
}

const book1:Book = {
    title: 'Oreily',
    type: { // Here we are defining the type and it knows what it is
        version: 2.50,
        bookBinding: 'E-Book',
        pages: 800
    }
}

You can also use the ? before accessing certain properties in an object if you're unsure whether the property exists, or you can use an if statement. This type of syntax is generally used when you are getting data from an API call.

console.log(book1.type?.version)

Type Union

Type Union is a way to build new types out of the existing types we have.

// For a function
function fetchValue(value: number | string | null){
    // do something here...
}

// For a variable
const num: number | null = null;

Here we are saying that the value parameter can be of number OR string OR null type. The | symbol is used to separate different values the parameter can take.

Type Assertions

We use assertions when fetching a resource from an API. Note that you only need to list the properties you intend to use in your application. So, even if the data returned by the API has thousands of properties, you only need to list the ones you are using.

interface Book{
    title: string;
}

async function fetchBook(url: string){
    const res = await fetch(url);
    const data = await res.json();
    return data as Book; // Here we are defining the type
}

You can also simply define it as const data: Book = await res.json().

Type Alias

Type alias is just a way that we give some sort of identifier for types. It is especially useful if you have a long type with many unions.

interface User{
    username: string;
    name: string;
    id: number;
}

type SearchType = string | number | User; // Alias

function fetchUserData(search: SearchType){ // Here we use type alias
    if(typeof search === 'string'){
        // Search by username
        console.log('Searching by username...')
    }else if(typeof search === 'number'){
        // Search by id
        console.log('Searching by id...')

    }else {
        // Search by using the search.name
        console.log('Searching by name...')
    }
}

fetchUserData('ramkumar12');

You can also define object properties using type aliases, but the downside is that you won't be able to extend these types.

interface Book{
    type: string;
    name: string;
}

interface Dictionary extends Book{
    index: number;
}

The extended type, in this case, Dictionary, will also have the properties type and name defined. It's like copying and pasting the properties from one interface to another.

I will cover generics in another blog as there is a lot to discuss. :)

Thank you for reading this blog. If you like my posts, follow me here and on my LinkedIn page.