The simplest way to define a custom type in TypeScript is to use the type alias
A type alias allows you to give a name to any type, whether it's a primitive, a union, a function, or an object.
This not only improves code readability but also makes it easier to manage and reuse types across your codebase.
Basic Syntax
The basic syntax for defining a custom type with the type alias is:
type AliasName = Type;
ts
We could also combine these types in a new Type for easier use
ts
In this example, User is a custom type alias that describes the shape of a User object. This makes it easy to define and enforce the structure of user-related data throughout our application.
This also gives us the advantage of being able to extend the User type into an Admin type by reusing the definition and adding new fields where necessary
ts
This let's us re-use sections of our code, making maintainability easier in the future.
We will look at type inheritance and extending types in detail in the next chapter.
Using Type Aliases with Functions
You can also use type aliases to define the shape of functions:
ts
In this example, Operation is a custom type alias for a function that takes two numbers as parameters and returns a number.
This can be useful for ensuring consistency in function signatures across our code.