type keyword in Typescript

Do you want to know how to use the Typescript this keyword? In this Typescript tutorial, I will explain to you how to use the type keyword in Typescript with a few real examples.

To use the ‘type’ keyword in TypeScript, you define a type alias that can represent a simple type, a union or intersection of types, or an object shape. This enhances code readability and maintainability. For example, type StringOrNumber = string | number; creates a type alias that can be either a string or a number, simplifying the usage of complex type annotations in your TypeScript code.

What is the “type” Keyword in TypeScript?

The ‘type’ keyword in TypeScript is used to declare a custom type alias. A type alias is essentially a name given to a type or a combination of types. It simplifies complex type annotations, making your code more readable and maintainable. The ‘type’ keyword can be used with primitives, arrays, objects, and even complex structures.

How to use the Typescript “type” keyword?

Here is a simple example of how to use the “type” keyword in Typescript.

type StringOrNumber = string | number;

let myVariable: StringOrNumber;
myVariable = 'Hello';  // Valid
myVariable = 123;      // Valid

In this example, StringOrNumber is a type alias for a union type that can be either a string or a number in the Typescript code.

You can also use ‘type’ to define more complex structures, like objects in Typescript.

type User = {
    name: string;
    age: number;
    isActive: boolean;
};

const user: User = {
    name: 'John Doe',
    age: 30,
    isActive: true
};

This example shows how ‘type’ can be used to define the shape of an object, making it easier to manage and understand object structures in your codebase.

See also  const Keyword in Typescript

Here is a complete example of how to use the type keyword in Typescript.

Let’s consider an example where we use the ‘type’ keyword in TypeScript to define a custom type and then use it in a function to see the output.

First, we’ll define a type alias named StringOrNumber which can be either a string or a number. Then, we’ll create a function named displayInfo that takes a parameter of this type and logs it to the console.

// Define a type alias
type StringOrNumber = string | number;

// Function that uses the StringOrNumber type
function displayInfo(input: StringOrNumber) {
    console.log(`The input is: ${input}`);
}

// Test the function with different types of inputs
displayInfo("Hello, TypeScript!");  // Pass a string
displayInfo(2023);                 // Pass a number

In this example, when you call displayInfo with different types of arguments (once with a string and once with a number), the function will log these values to the console, demonstrating how the StringOrNumber type alias works in practice.

You can see the output after I ran the code using Visual Studio Code:

type keyword in Typescript

When to Use ‘type’ Over ‘interface’ in Typescript

The choice between ‘type’ and ‘interface’ can sometimes be confusing in Typescript. As a rule of thumb, use ‘type’ to define a union or intersection type or a type that cannot be extended or implemented. Use ‘interface’ to define the shape of an object that can be extended or implemented.

Example of Union Type with ‘type’ in Typescript

type Coordinates = [number, number];
type NamedLocation = { name: string; coordinates: Coordinates };
type GeoLocation = Coordinates | NamedLocation;

const location1: GeoLocation = [45.0, 75.0];            // Valid
const location2: GeoLocation = { name: "Central Park", coordinates: [40.785091, -73.968285] };  // Valid

Best Practices for Using ‘type’ in TypeScript

  1. Consistency: Be consistent in your use of ‘type’ and ‘interface’. Mixing them unnecessarily can lead to confusion.
  2. Readability: Choose clear and descriptive names for your type aliases.
  3. Modularity: Break down complex types into smaller, reusable types to keep your codebase clean and manageable.
See also  Typescript check if a string contains a substring

Conclusion

The ‘type’ keyword in TypeScript is a powerful tool for creating custom types and enhancing the type safety of your code. Understanding its usage, especially when compared to ‘interface’, is key to writing effective and maintainable TypeScript code. I hope you got an idea of how to use the “type keyword in Typescript“.

You may also like:

>