Custom Types in TypeScript

Learn via video courses
Topics Covered

Overview

TypeScript is a strongly typed programming language in which everything has a type whether it is a variable or a function. There can be instances when we want to make an object that has a particular format or a function returns a certain format. There comes the existence of custom types that can be used in our code. They are those types that can be used where programs have complex data structures and declaring your type will help you to address the complexity.

Introduction

When a variable is initialized, we assign some value to that variable and we want to know the type of value assigned to that variable which is further dependent upon the datatype of that variable. TypeScript supports different types of datatypes:

  • Built-in Types: Five built-in data types are given below:

    • Number: All numbers in TypeScript are stored as floating-point values. These values are specified like a number data type.
    • String: It is used to represent text in TypeScript. We include string literals in our scripts by enclosing them in single or double quotation marks.
    • Boolean: This data type has only two values: true or false. A boolean value is a truth value that specifies whether a condition is true or not.
    • Void: It is a return type of function that doesn't return any value. It is used when no data type is available.
    • Null: It represents a variable whose value is undefined. It has only one value which is null.
  • User-defined Data Types: Various user-defined data types are given below:

    • Array: Array is a collection of elements of a similar data type. TypeScript supports working with arrays of values.
    • Tuple: It is a data type that includes two sets of values of different data types.
    • Interface: An interface tells the compiler which property names an object can have. It defines properties, methods, and, events that are the members of interfaces.
    • Class: A class is a blueprint or template by which we can create objects with specific properties and methods. It's used to create reusable components.
    • Functions: It is a logical block of code that is used to organize a program. They ensure that our program should be readable, reusable, and maintainable.
    • Enums: It defines a set of named constants. TypeScript supports both numeric-based and string-based enums.

Custom Types

TypeScript allows defining our own data types, that we can use in our code. Custom types are the creation of your types based on the basic data types that allow you to ensure the type checker validates the data structures specific to your project. This may reduce the chance of bugs in our project, and also allows better documentation of data structures that are used in our code.

Use of Custom Types

Suppose we have a function that always returns data in a specified format, and uses API to get that data. If the API returns the data in the wrong format, we don't want the wrongly formatted data to end up in our code which could create further problems. In that case, the returned function conforms to a certain type. So, we have to define our custom types.

Custom Type Syntax

We use the type keyword to create a custom type followed by the type name and an assignment to a {} block with the type properties.

The above syntax depicts an object literal where a type coder is defined that must be an object with the name key that holds a string value and a knownFor key that holds an array of strings.

Code Examples of Custom Types

Custom Types

Output

In the above snippet, the ada constant will pass through the type checker without throwing an error.

Nested Custom Types

We can also nest custom types together.

This code will pass the type checker as the manager constant fits the type that is designated for the manager field. We can exclude the type in the manager because it has the same shape as the User type. TypeScript compiler doesn't throw errors when we use an object with the same shape as the one expected by the type of manager property, even if it is not set to have the User type.

Optional Properties

Optional Properties are used when we have to pass the type checker with or without any value. To add these properties to a type, add the ? modifier to the property.

In the above snippet, the Person object can be constructed and defined without using the optional fields as well.

Type Assertions of Custom Type

We can use the any type as the type of any value, that doesn't provide the strong typing needed to get the full advantage of the language. In the end, you may end up with some variables bound to any that are outside our control. This may happen when we use external dependencies that are not written in TypeScript or that do not have type declaration available. So to make our code type-safe from these scenarios, we use Type Assertions that are used to change the type of a variable to another type. These are used by adding as NewType after the variable. This changes the type of variable to that specified after the as keyword.

In the above snippet, valA has the type any, by using the as keyword, this code forces the valB to have the type string.

Key Takeaway

To assert a variable of typeA to have typeB, typeB should be a subtype of typeA. Most of the TypeScript types are a subtype of any excluding never.

Conclusion

  • Creating custom types to represent the data structures used in our code is very useful and provides flexibility in our project.
  • By increasing the type-safety of our code as a whole, having our types improves the developer's experience when working with teammates on the same code base.
  • We came to know about the uses and syntax of Custom Types.
  • We get to know about Nested Custom Types and Optional Properties through some code examples.
  • Hope this article has provided you with the relevant information regarding Custom types and their importance in the TypeScript code.