DEV Community

Cover image for TypeScript Data Types - Comprehensive Guide
Tanvir Ahmed
Tanvir Ahmed

Posted on

TypeScript Data Types - Comprehensive Guide

TypeScript provides a robust type system built on top of JavaScript, helping ensure the accuracy of your code's types. In this guide, we will explore both primitive and non-primitive data types in TypeScript, complete with explanations and examples.

❏ Primitive Data Types

Primitive data types are the most basic types in TypeScript, and they represent single values. These types are immutable, meaning their values cannot be changed once set. TypeScript supports the following primitive data types:

1️⃣ Any

The any type is a special type in TypeScript that allows you to store values of any type. It is used when you are unsure about the type of a variable.

let data: any;
data = "Hello, world!";   // string
data = 42;                // number
data = { key: "value" };  // object
data = [1, 2, 3];         // array
Enter fullscreen mode Exit fullscreen mode

2️⃣ Number

The number type is used for numerical values, both integers and floating-point numbers.

let age: number = 25;
let price: number = 199.99;
Enter fullscreen mode Exit fullscreen mode

3️⃣ String

The string type is used to represent text (sequences of characters).

let name: string = "John";
let greeting: string = "Hello, world!";
Enter fullscreen mode Exit fullscreen mode

4️⃣ Boolean

The boolean type represents true or false values.

let isActive: boolean = true;
let isComplete: boolean = false;
Enter fullscreen mode Exit fullscreen mode

5️⃣ undefined

The undefined type is used when a variable is declared but not assigned a value.

let notAssigned: undefined = undefined;
Enter fullscreen mode Exit fullscreen mode

6️⃣ null

The null type is used to indicate that a variable has no value.

let emptyValue: null = null;
Enter fullscreen mode Exit fullscreen mode

❏ Non-Primitive Data Types

Non-primitive data types in TypeScript (also called reference types) are used to store collections of values or more complex structures. Unlike primitive types, non-primitive types are mutable (can be changed), and they store references to the values in memory, not the actual values themselves.

1️⃣ Array Data Type

An array holds a collection of values of a specific type. TypeScript provides two ways to declare an array:

let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: Array<string> = ['apple', 'banana', 'cherry'];
Enter fullscreen mode Exit fullscreen mode

Array with Mixed Types:

let mixedArray: (number | string)[] = [1, 'apple', 2, 'banana'];
Enter fullscreen mode Exit fullscreen mode

2️⃣ Object Data Type

An object in TypeScript is a collection of key-value pairs where each key is a string and each value can be of any type.

emample:01

const user = {
  firstName: "John",
  lastName: "Doe",
};
Enter fullscreen mode Exit fullscreen mode

emample:02

const user2: {
  company: "Programming Here";
  firstName: string;
  middleName?: string;  // Optional property
  lastName: string;
  isMarried: boolean;
} = {
  company: "Programming Here",
  firstName: "Tanvir",
  lastName: "Soysov",
  isMarried: true,
};
Enter fullscreen mode Exit fullscreen mode

3️⃣ Function Data Type

Functions in TypeScript can be typed by defining the types of parameters and return values.

Function Example:

function add(a: number, b: number): number {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

❏ Other Types

1️⃣ unknown Data Type

The unknown type in TypeScript is a type-safe version of any. When a variable's type is unknown, TypeScript enforces that you cannot perform operations on it until you explicitly check its type.

const handleData = (data: unknown) => {
    if (typeof data === 'string') {
        console.log("String length:", data.length);
    } else if (typeof data === 'number') {
        console.log("Number squared:", data * data);
    } else {
        console.log("Unknown type");
    }
};
handleData("hello");    // String length: 5
handleData(4);          // Number squared: 16
Enter fullscreen mode Exit fullscreen mode

2️⃣ Nullable Data Type

A nullable type in TypeScript means that a variable can either have a value or be null or undefined.

const searchName = (value: string | null) => {
    if (value) {
        console.log("Searching for:", value);
    } else {
        console.log("There is nothing to search.");
    }
};
Enter fullscreen mode Exit fullscreen mode

3️⃣ Never Data Type

The never type is used when a function never returns a value. This typically happens when a function throws an error or has an infinite loop.

const throwError = (message: string): never => {
    throw new Error(message);
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

TypeScript's type system enables developers to write safer and more robust code. By understanding and using both primitive and non-primitive data types, as well as special types like any, unknown, nullable, and never, you can harness the full power of TypeScript in your projects.

Top comments (0)