What is TypeScript? TypeScript defined
TypeScript is a variation of the popular JavaScript programming language that adds some key features that are important for enterprise development. In particular, TypeScript is strongly typed — that is, variables and other data structures can be declared to be of a specific type, like a string or a boolean, by the programmer, and TypeScript will check the validity of their values. This isn’t possible in JavaScript, which is loosely typed.
TypeScript’s strong typing makes possible a number of features that help make developers more efficient, especially when dealing with large, enterprise-scale codebases. TypeScript is compiled, rather than interpreted like JavaScript, which means errors can be caught before execution; IDEs that perform background incremental compilation can spot such errors during the coding process.
Despite this key difference to JavaScript, TypeScript can still be executed anywhere JavaScript can run. That’s because TypeScript compiles not to a binary executable, but to standard JavaScript. Let’s dive in to find out more.
TypeScript vs. JavaScript
TypeScript is a superset of JavaScript. While any correct JavaScript code is also correct TypeScript code, TypeScript also has language features that aren’t part of JavaScript. The most prominent feature unique to TypeScript—the one that gave TypeScript its name—is, as noted, strong typing: a TypeScript variable is associated with a type, like a string, number, or boolean, that tells the compiler what kind of data it can hold. In addition, TypeScript does support type inference, and includes a catch-all any type, which means that variables don’t have to have their types assigned explicitly by the programmer; more on that in a moment.
TypeScript is also designed for object-oriented programming—JavaScript, not so much. Concepts like inheritance and access control that are not intuitive in JavaScript are simple to implement in TypeScript. In addition, TypeScript allows you to implement interfaces, a largely meaningless concept in the JavaScript world.
That said, there’s no functionality you can code in TypeScript that you can’t also code in JavaScript. That’s because TypeScript isn’t compiled in a conventional sense—the way, for instance, C++ is compiled into a binary executable that can run on specified hardware. Instead, the TypeScript compiler transcodes TypeScript code into functionally equivalent JavaScript. This article from Sean Maxwell on GitConnected has some great examples of object-oriented TypeScript code snippets and their JavaScript equivalents. The resulting JavaScript can then be run anywhere any JavaScript code can run, from a web browser to a server equipped with Node.js.
So if TypeScript is, in the end, just a fancy way to generate JavaScript code, why bother with it? To answer that question, we need to look at where TypeScript came from and what it’s used for.
What is TypeScript used for?
TypeScript was released as open source in 2012 after being developed within Microsoft. (The software giant remains the project’s steward and main developer.) This ZDNet article from the time offers an intriguing look into why that happened: “It turns out one of the big motivations was the experience of other teams at Microsoft who were attempting to develop and maintain Microsoft products in JavaScript.”
At the time, Microsoft was trying to scale up Bing Maps as a competitor to Google Maps, as well as to offer web versions of its Office suite—and JavaScript was the primary development language for the tasks. But the developers, in essence, found it difficult to write apps on the scale of Microsoft’s flagship offerings using JavaScript. So they developed TypeScript to make it easier to build enterprise-level applications to run in JavaScript environments. This is the spirit behind the tagline for the language on the official TypeScript project site: “JavaScript that scales.”
Why is TypeScript better for this kind of work than vanilla JavaScript? Well, we can argue forever about the merits of object-oriented programming, but the reality is that many software developers who work on big enterprise projects are used to it, and it helps with code reuse as projects balloon in size. You also shouldn’t neglect the extent to which tooling can boost developer productivity. As noted, most enterprise IDEs support background incremental compilation, which can spot errors as you work. (As long as your code is syntactically correct, it will still transpile, but the resulting JavaScript may not work properly; think of the error checking as the equivalent of spellcheck.) These IDEs can also help you refactor code as you get deep into your project.
In short, TypeScript is used when you want the enterprise features and tools of a language like Java, but you need your code to execute in a JavaScript environment. In theory, you could write the standard JavaScript that the TypeScript compiler generates yourself, but it would take you much longer and the codebase would be more difficult for a large team to collectively understand and debug.
Oh, and TypeScript has another neat trick up its sleeve: You can set the compiler to target a specific JavaScript runtime environment, browser, or even language version. Since any well-formed JavaScript code is also TypeScript code, you could, for instance, take code written to the ECMAScript 2015 spec, which included a number of new syntactical features, and compile it into JavaScript code that would be compliant with legacy versions of the language.
Install TypeScript
Ready to start playing with TypeScript? Installing the language is easy. If you already use Node.js on your development machine, you can use NPM, the Node.js package manager, to install it. The official TypeScript in 5 minutes tutorial will walk you through the process.
TypeScript can also be installed as a plug-in to your IDE of choice, which will give you the tooling advantages we talked about above and also take care of the process of compiling TypeScript to JavaScript. Since TypeScript was developed by Microsoft, it’s unsurprising that there are high-quality plug-ins available for Visual Studio and Visual Studio Code. But as an open source project, TypeScript has been adapted everywhere, ranging from open source IDEs like Eclipse to venerable text editors like Vim. And the whole project can be browsed and downloaded from GitHub.
TypeScript syntax
Once TypeScript has been installed, you’re ready to start exploring, and that means understanding the basics of TypeScript syntax. Since JavaScript is the foundation of TypeScript, you need to be familiar with JavaScript before you begin. No doubt your main points of interest will be the TypeScript-specific features that make the language unique; we’ll touch on the high points here.
TypeScript types
Obviously the most important syntactic feature in TypeScript is the type system. The language supports a number of basic types:
- Boolean: A simple true/false value.
- Number: In TypeScript, as in JavaScript, all numbers are floating point values—there’s no separate integer. TypeScript supports decimal, hexadecimal, binary, and octal literals.
- String: A string of textual data. You can use single or double quotes to surround your string when setting the data. You can also use backticks (
`
) to surround strings with multiple lines, and you can embed expressions in a string with the syntax${ expr }
. - Arrays and tuples: These types let you store multiple values in a specified sequence. In an array, the individual values are all of the same data type, whereas in a tuple they can be heterogenous. The TypeScript
forEach()
method is used to call a function on each element in an array. - Enum: Like the type of the same name in C#, a TypeScript enum lets you assign human-readable names to a sequence of numeric values.
- Any: This is a type for a variable where you don’t necessarily know what value it will end up with in advance—it may take its values from user input or a third-party library, for example.
- Object: This is the type that represents anything that’s not a primitive type; it’s essential to the object-oriented nature of TypeScript.
There are two different ways to explicitly assign a type to a variable. The first is angle bracket syntax:
let someValue: any ="this is a string";
let strLength: number = (<string>someValue).length;
And the second is as
syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
These code snippets, which are taken from the TypeScript documentation, are functionally equivalent. Both define someValue
as a variable of type any
and assign "this is a string"
as its value, then define strLength
as a number and assign as its value the length of the contents of someValue
.
TypeScript types can also be set by inference. That is, if you set a value of x to 7 without establishing what type x is, the compiler will assume x should be a number. Under some circumstances the compiler may infer an any
type, though you can use compilation flags to ensure that it doesn’t.
The TypeScript type system is quite rich and goes beyond the scope of this article. There are a number of advanced and utility types; these include union types, which allow you to establish that a variable will be one of several specified types, and mapped types, which are types you can create based on an existing type, in which you transform each property in the existing type in the same way. For instance, you could create a union type for a variable that you want to be either a number or a boolean, but not a string or anything else; or you could create a mapped type that sets all the elements in an array to read only.
TypeScript interface
Like most object-oriented languages, TypeScript has interfaces, which allow users to define their own types. Interfaces establish the properties that an object has, along with the types associated with those properties. TypeScript interfaces can have optional properties. For more on the syntax, check out the TypeScript documentation.
TypeScript generics
TypeScript also shares the concept of generics with object-oriented languages like Java and C#. (The equivalent facility in C++ is called a template.) In TypeScript, generic components can work over a variety of types, rather than just one, depending on where in the code those components are called. Here’s a very simple example from the TypeScript documentation. First, consider this function, which takes in an argument and then immediately returns it:
function identity(arg: any): any {
return arg;
}
Because the function is defined with the any
type, it will accept an argument of whatever type you choose to throw at it. However, what it returns will be of the any
type. Here’s a version of the function using generics:
function identity<T>(arg: T): T {
return arg;
}
This code includes the type variable T
, which captures the type of the incoming argument and stores it for our later use.
There is a lot more to generics, which are key to making code reuse possible in big enterprise project. Check out the TypeScript documentation for the details.
TypeScript class
In object-oriented programming, classes inherit functionality, and in turn serve as the building blocks of objects. JavaScript traditionally did not make use of classes, instead relying on functions and prototype-based inheritance, but the concept was added to the language as part of the ECMAScript 2015 version of the standard. Classes had already been part of TypeScript, and now TypeScript uses the same syntax as JavaScript. One of the benefits of TypeScript’s compiler is that it can transform code with JavaScript classes into legacy JavaScript code that conforms with pre-2015 standards.
TypeScript date
There are a number of methods and objects available for getting and setting the date and time in TypeScript, mostly inherited from JavaScript. JavaTPoint has a good rundown of how this works.
TypeScript tutorial
Ready to go deeper? Get up to speed with these TypeScript tutorials:
- TypeScript in 5 Minutes will walk you through the process of installing TypeScript if you haven’t already.
- This Visual Studio Code tutorial demonstrates how IDEs really add to your TypeScript development productivity.
- TypeScript Tutorial for Beginners: The Missing Guide is a really thorough introduction that will be useful even if you have fairly limited JavaScript experience.
If you’re looking to learn how to use TypeScript with React, The JavaScript library for building UIs developed by Facebook, check out How to use TypeScript with React and Redux from Ross Bulat and the section on React and webpack in the TypeScript documentation. Happy learning!