TypeScript Data Types

TypeScript provides a variety of data types to ensure type safety and improve code quality. These data types allow developers to define the kind of data that variables, function parameters, and return values will hold.

 

Basic Data Types

Number

The number type is used for numeric values, including integers and floating-point numbers.

let age: number = 25;
let pi: number = 3.14;
console.log(age, pi); // Output: 25 3.14

String

The string type is used for text data, enclosed in single (') or double (") quotes.

let name: string = "John Doe";
console.log(`Hello, ${name}`); // Output: Hello, John Doe

Boolean

The boolean type represents true or false.

let isActive: boolean = true;
console.log(isActive); // Output: true

 

Special Data Types

Any

The any type allows a variable to hold any type of data. It bypasses type-checking.

let anything: any = "Hello";
anything = 42; // No error
console.log(anything); // Output: 42

Unknown

The unknown type is safer than any because it enforces type checking before operations.

let unknownValue: unknown = "Test";
if (typeof unknownValue === "string") {
  console.log(unknownValue.toUpperCase()); // Output: TEST
}

Null and Undefined

The null and undefined types are subtypes of all other types.

let empty: null = null;
let notAssigned: undefined = undefined;
console.log(empty, notAssigned); // Output: null undefined

 

Advanced Data Types

Array

Arrays in TypeScript can store multiple values of the same type.

let numbers: number[] = [1, 2, 3, 4];
console.log(numbers); // Output: [1, 2, 3, 4]

Tuple

A tuple is an array with fixed types and a specific number of elements.

let person: [string, number] = ["Alice", 30];
console.log(person); // Output: ["Alice", 30]

Enum

Enum allows defining a set of named constants.

enum Direction {
  Up,
  Down,
  Left,
  Right,
}
let move: Direction = Direction.Up;
console.log(move); // Output: 0

Object

The object type represents non-primitive types like objects.

let user: { name: string; age: number } = { name: "Bob", age: 28 };
console.log(user); // Output: { name: "Bob", age: 28 }

Union

The union type allows a variable to hold more than one type.

let id: string | number;
id = 123; // Valid
id = "ABC"; // Valid
console.log(id);

Void

The void type is used for functions that do not return any value.

function logMessage(message: string): void {
  console.log(message);
}
logMessage("Hello, TypeScript!"); // Output: Hello, TypeScript!

Never

The never type represents a value that never occurs, often used for errors or infinite loops.

function throwError(message: string): never {
  throw new Error(message);
}

 

Summary

TypeScript provides a rich set of data types, including basic types like number, string, and boolean, as well as advanced types like tuple, enum, and union. Using these types ensures better type safety and improves code maintainability in TypeScript applications.