What is TypeScript?
The Basics of TypeScript
In this example we look at the real power of TypeScript: using custom class types to improve code readability and maintainability. In this code a custom type is used for both the method’s input parameter and return variable.
The Magic of Transpilers
Advanced TypeScript Concepts
A tuple is a special kind of array with a fixed number of elements whose types are known but do not need to be the same. The code below shows how to create a tuple and assign a value. Take note, the third line generates a compiler error because the order of the types is different than how the tuple variables are defined.
Another powerful concept borrowed from other languages such as C# or C++ is the enum type. Enums allow you to greatly increase the readability of your code by using known string descriptions over magic numbers.
One of the core tenants of TypeScript is that type-checking focuses on the shape that values have. This is referred to as “duck typing” or “structural subtyping.” In TypeScript you utilize interfaces to define a contract that enforces this concept and makes it easier to fully utilize other advanced concepts, such as inheritance and generics.
Generics are a very powerful concept that allows you to reuse code by creating generic methods or classes that have commonality across types. Looking at the example, we can see two common ways of using generics. The first block of code has a simple generic method that takes in a parameter of T. The type definition of T is based on the type the calling code passes.
Where generics really shine is when you apply constraints. Coupling this with the use of interfaces allow you to create powerful reusable components that greatly increase the readability of maintainability of your code base. The example showcases how to apply a constraint using an interface. By doing this, only classes that implement the ISearchInfo interface can be passed to the logSearch method.
Want to learn more?
Though a few of us (myself included) were a little slow to realize the true benefits of TypeScript. There’s no denying TypeScript has become a crucial tool for building modern web applications. It allows you to greatly improve the readability and maintainability of your code base.
Hopefully this article has piqued your interest in learning more about TypeScript and adding it to your toolbelt for building both client and server applications.
Here are the best places to learn more about TypeScript:
Lastly, if you still have any questions about how TypeScript can help, please feel free to reach out to us at any time. We’d love to help you get started.