How to Use Types in TypeScript Explained for Beginners

TypeScript introduces static typing to JavaScript, which helps catch errors during development and improves code quality. This article will guide you through the basics of using types in TypeScript, making it easier for beginners to understand how to leverage TypeScript's type system.

What Are Types in TypeScript?

Types in TypeScript help define the shape and structure of data. By specifying types, you ensure that variables, function parameters, and return values adhere to expected formats. This can prevent many common programming errors.

Basic Types

TypeScript provides several basic types that you can use to define variables and functions:

  • Number: Represents numeric values.
  • String: Represents textual data.
  • Boolean: Represents true or false values.
  • Array: Represents a collection of values of a specific type.
  • Object: Represents a collection of key-value pairs.

Number Example

let age: number = 30;

String Example

let name: string = "John Doe";

Boolean Example

let isStudent: boolean = true;

Array Example

let scores: number[] = [85, 90, 78];

Object Example

let person: { name: string, age: number } = {
  name: "Jane Doe",
  age: 28
};

Type Inference

TypeScript can automatically infer types based on the assigned values. This means you don’t always need to explicitly specify types, although doing so can enhance code clarity.

Type Inference Example

let count = 10; // TypeScript infers count as number
count = "text"; // Error: Type 'string' is not assignable to type 'number'

Custom Types with Interfaces

Interfaces in TypeScript allow you to define custom types with a specific structure. They are particularly useful for creating complex objects and ensuring consistent shapes across your application.

Interface Example

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

let employee: Person = {
  name: "Alice",
  age: 32
};

Union Types

Union types allow a variable to hold values of multiple types. This can be useful when a value can be one of several types.

Union Type Example

let id: number | string;
id = 123; // valid
id = "abc"; // valid
id = true; // Error: Type 'boolean' is not assignable to type 'number | string'

Type Aliases

Type aliases let you create a new name for a type. This can be helpful for simplifying complex type definitions.

Type Alias Example

type ID = number | string;

let userId: ID;
userId = 456; // valid
userId = "xyz"; // valid

Conclusion

Using types in TypeScript provides numerous benefits, including early error detection, improved code readability, and enhanced maintainability. By understanding basic types, type inference, interfaces, union types, and type aliases, you can start leveraging TypeScript to write more robust and reliable code. As you gain more experience with TypeScript, you’ll discover even more advanced features and patterns that can further enhance your development process.