A Beginner's Guide to Types in TypeScript: Understanding and Using Type Annotations

nishanthan-k

Nishanthan K

Posted on November 13, 2024

A Beginner's Guide to Types in TypeScript: Understanding and Using Type Annotations

Understanding Types in TypeScript

TypeScript is a statically typed superset of JavaScript, bringing the power of types to a language traditionally known for its flexibility. By using types in TypeScript, we can write safer, more predictable code that catches errors during development instead of at runtime. In this article, we’ll cover the various types available in TypeScript, along with examples to illustrate each.

Primitive Types

Primitive types represent basic data values, similar to JavaScript primitives. These include number, string, boolean, null, undefined, and symbol.

Example

let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
let empty: null = null;
let unknownValue: undefined = undefined;
Enter fullscreen mode Exit fullscreen mode

Each variable here has a type annotation (: number, : string, etc.), helping us ensure that only values of the specified type can be assigned.

Object Types

Object types allow us to define complex data structures by specifying the types of properties within an object.

Example

type Person = {
  name: string;
  age: number;
  isStudent: boolean;
};

let person: Person = {
  name: "Bob",
  age: 20,
  isStudent: true,
};
Enter fullscreen mode Exit fullscreen mode

In this example, the Person type requires name, age, and isStudent properties, each with its specific type.

Array Types

Arrays in TypeScript can be typed to hold elements of specific types. We can use either Type[] or Array syntax.

Example

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
Enter fullscreen mode Exit fullscreen mode

Here, numbers can only contain numbers, and names can only contain strings.

Tuple Types

Tuples allow us to define arrays with fixed types and lengths, where each element can have a different type.

Example

let student: [string, number] = ["Alice", 22];
Enter fullscreen mode Exit fullscreen mode

The student tuple has a fixed structure: a string followed by a number.

Enum Types

Enums are a way to define a set of named constants, making our code more readable and maintainable.

Example

enum Color {
  Red,
  Green,
  Blue,
}

let favoriteColor: Color = Color.Green;
Enter fullscreen mode Exit fullscreen mode

Here, Color is an enum with three values: Red, Green, and Blue.

Union Types

Union types allow a variable to hold values of multiple specified types, offering greater flexibility.

Example

let id: string | number;
id = "123"; // valid
id = 123;   // valid
Enter fullscreen mode Exit fullscreen mode

With string | number, id can be either a string or a number.

Intersection Types

Intersection types combine multiple types into one. The resulting type will have all the properties of the intersected types.

Example

type Car = {
  make: string;
  model: string;
};

type Electric = {
  batteryRange: number;
};

type ElectricCar = Car & Electric;

let tesla: ElectricCar = {
  make: "Tesla",
  model: "Model 3",
  batteryRange: 300,
};
Enter fullscreen mode Exit fullscreen mode

In this example, ElectricCar has properties from both Car and Electric.

Literal Types

Literal types allow a variable to hold a specific value, which can be useful in certain situations, such as limiting input options.

Example

let answer: "yes" | "no";
answer = "yes"; // valid
answer = "no";  // valid
// answer = "maybe"; // invalid
Enter fullscreen mode Exit fullscreen mode

The variable answer can only have the values "yes" or "no".

Type Aliases

Type aliases allow you to create custom names for complex types, improving code readability and reuse.

Example

type Point = {
  x: number;
  y: number;
};

let position: Point = {
  x: 10,
  y: 20,
};
Enter fullscreen mode Exit fullscreen mode

Here, Point is a type alias for an object with x and y properties.

Interface

Interfaces are similar to type aliases but specifically for defining object structures. They are extendable, meaning they can be used to create hierarchies of types.

Example

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

interface Admin extends User {
  role: string;
}

let admin: Admin = {
  name: "Alice",
  age: 30,
  role: "superadmin",
};
Enter fullscreen mode Exit fullscreen mode

Interfaces are a great way to define and extend object shapes in a scalable way.

Type Assertions

Type assertions allow us to override TypeScript’s inferred type system. They are especially useful when we know more about a value than TypeScript can infer.

Example

let value: any = "Hello, TypeScript!";
let strLength: number = (value as string).length;
Enter fullscreen mode Exit fullscreen mode

Using (value as string), we tell TypeScript to treat value as a string, allowing us to access string-specific properties.

Conclusion

Understanding types in TypeScript is crucial for leveraging its benefits, including safer code and better development experiences. By mastering these various types, you can build robust applications and make the most of TypeScript’s powerful type system.

💖 💪 🙅 🚩
nishanthan-k
Nishanthan K

Posted on November 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related