TypeScript in 4 lines of code
Really, that’s it. There’s so much power in just those four lines of code.
Before we breakdown the above code, it’s probably worthwhile to talk a little bit about TypeScript and what it is. More importantly, let’s talk about what TypeScript isn’t.
Let’s start with the first line:
Interfaces in any programming language of course allow you to describe the structure of data or some other object. It’s a contract, and when something is declared as a type of that interface you as the developer knows what’s there. In addition, because the IDE, such as Visual Studio Code, you can get autocomplete and IntelliSense when using variables declared as the interface type.
Let’s bring back the entire code block:
You’ll notice the declarations of
text: string and
message: Message. By using
variableName: type, we’ve told TypeScript what type we want the variable to be. This brings a couple of great advantages. The first is pretty obvious - that your IDE will let you know when you’re using it wrong. The second is by indicating the data type, your IDE can offer autocomplete or, in the case of Visual Studio Code, IntelliSense.
Don’t underestimate how important IntelliSense is. While through use and repetition, you absolutely will start to remember various property and method names. But for those edge cases where you need to call something you don’t often reach for, being able to simply hit “dot” and scroll through the list of options (often with documentation) is much more efficient than opening the docs or searching Stack Overflow.
In our little application, we created our own interface, so it seems only logical that VS Code would know what to do with that. But what about other packages, such as Express, Restify, or Mongoose?
Definitely Typed is a community that creates
package.d.ts files, which contain the list of interfaces and structures provided by a particular package. These types are installable via NPM, and are almost always solely needed as dev dependencies. To install a package’s types, simply prepend the name of the package with
@types/. Note that while not every package has types created, I think you’ll be pleasantly surprised at how many have been done.
As an example, here’s how you’d install the types for Restify.
When declaring our message variable, we used the keyword
let in TypeScript, the variable
x in the above scenario would not be available outside of the if block.
tsc, which is available after installing TypeScript (which can be done via NPM).
There are numerous reasons to use TypeScript. Not having to worry about versioning issues, being able to take advantage of the latest technologies, and many other features, make creating projects in TypeScript rather compelling. For me, the chief is the ability to have typed objects. It makes me a more efficient developer, and helps me spot bugs that much faster.