DEV Community

Cover image for What is TypeScript and why should you use it?
Harshil Agrawal for Contentful

Posted on • Originally published at contentful.com

What is TypeScript and why should you use it?

NOTE: This article originally appeared on the Contentful Blog

I’ve been learning and using TypeScript for the past year for various projects, and I have been enjoying it. TypeScript provides a great developer experience, and I believe that it has increased my productivity. I don’t have to manually check for errors every time a change gets made, and the inline documentation helps me ship faster. In this article, I will give you an overview of TypeScript, share some of its features, and help you get started.

Before learning about TypeScript, let’s take a step back and revisit JavaScript. Since the earliest days of the World Wide Web, JavaScript has been used to make websites interactive – handle mouse and keyboard events, validate forms, and so on. With time, the language evolved. You can now use JavaScript to build websites and apps for any platform. It can be used to code both the frontend and backend of your website/app. You can build cross-platform apps using React Native and desktop apps with Electron, and you can even use JavaScript for your next IoT project!

With these extensive use cases, the complexity in the codebase increased. For smaller projects, using JavaScript is still fine. However, for larger projects, it became difficult to debug the code and catch errors.

What is the difference between TypeScript and JavaScript?

TypeScript is a superset of JavaScript. It means that TypeScript provides all the features and functionalities of JavaScript with some added features. TypeScript compiles to JavaScript, which the browser understands. TypeScript provides “type safety” (hence the name!) to JavaScript. It was created by Microsoft and is open source. If you’re interested in contributing or just going through the source code, you can find the repository on GitHub.

To understand type safety, consider an example where you define a variable name. In JavaScript, you would use a similar code as below:

var name = "Harshil"
Enter fullscreen mode Exit fullscreen mode

Since this is a variable name and we haven’t defined its type, this variable can have any value. It doesn’t matter if it’s a string, number, boolean, or object. Hence, the below code will execute without errors:

name = 17

name = false

name = {
first: "Harshi",
last: "Agrawal:
}
Enter fullscreen mode Exit fullscreen mode

Using TypeScript, you can define the type string for the variable name, as below:

var name :string = "Harshil"
Enter fullscreen mode Exit fullscreen mode

If you change its value to any other type, the compiler returns an error. Type safety saves a lot of debugging time and helps in keeping the code consistent.

Features of TypeScript

TypeScript extends JavaScript and improves the developer experience. It enables developers to add type safety to their projects. Moreover, TypeScript provides various other features, like interfaces, type aliases, abstract classes, function overloading, tuple, generics, etc. Explaining all the features is out of the scope of this article. However, I will present two that I find useful.

Interface

You receive an object when you call any Contentful API. This object response contains the necessary data that you need. Similar to the Contentful API, other APIs also send an object as a response.

Interfaces get used to ensure that the object contains the required data with the correct data type. This object can be a response or request body or parameters for a function.

An interface has the following syntax:

interface interfaceName {
    variableOne: type;
    variableTwo: type;
}
Enter fullscreen mode Exit fullscreen mode

Using the above syntax, we can create an interface Profile with the properties name and social.

interface Profile {
    name: string;
    social: string;
}
Enter fullscreen mode Exit fullscreen mode

The above interface can be used as follow:

function hello (params: Profile) {
    return "Find " + params.name + " here " + params.social
}
Enter fullscreen mode Exit fullscreen mode

The above is a simple example of interfaces. There are various other functionalities that interfaces provide. You can set optional properties, extend interfaces to add new properties, and more. To learn more about interfaces, refer to the TypeScript documentation.

Literal Types

Another feature that I find useful is Literal Types. Though, by themselves, they’re not so useful. But one can combine them into unions, which makes the Literal Types useful.

The following example demonstrates the syntax of Literal Types.

let social: "twitter" = "harshil1712"
Enter fullscreen mode Exit fullscreen mode

Here, the variable social has the type “twitter.” However, this isn’t useful on its own.

function greet(message: string, name: "Alice" | "Bob" ){
    //...
}
greet("Hello", "Alice" );
greet("Hey", "Bob");
greet("Hey", "Max"); // Argument of type '"Max"' is not assignable to parameter of type '"Alice" | "Bob"'.
Enter fullscreen mode Exit fullscreen mode

In the above function, the second parameter can only take values that have the type of either “Alice” or “Bob.” This helps us in writing functions that only accept a certain set of known values. They can do much more with Literal Types. Read the official documentation to learn more.

How to use TypeScript?

Now that you have a basic understanding of what TypeScript is, in this section, you will learn how to use TypeScript.

Browsers don’t understand TypeScript. They understand JavaScript code. Hence, the TypeScript code needs to get compiled into JavaScript, and for that, you need the TypeScript compiler.

You can install TypeScript globally using the following npm command. The global installation allows you to run the tsc command anywhere from your terminal.

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

Once you have installed TypeScript, create an index.ts file and add the following code:

let message:string = "Hello, World!"

function greeting () {
    console.log(message);
}

greeting()
Enter fullscreen mode Exit fullscreen mode

The above code declares a variable message and creates a function that logs the message to the console. To run this code, you have to compile it to JavaScript. Run the following command:

tsc index.ts
Enter fullscreen mode Exit fullscreen mode

You’ll observe that the compiler creates an index.js file with the compiled code.

The TypeScript compiler is flexible and allows you to configure options like the target JavaScript version. At the time of writing this article, the default target is es3.

To configure the compiler options, you can either pass them with the CLI command or create a tsconfig.json. You can learn more about the various configuration options on the TSConfig Reference documentation page.

If you want to use TypeScript in your next Contentful project, we released contentful.js v10 in Beta with enhanced TypeScript support. Check out the changelog and let us know what you think!

Advantages of using TypeScript

TypeScript extends JavaScript, providing a better developer experience. The benefits of using TypeScript over JavaScript include:

  • Static typing – TypeScript comes with optional static typing and a type inference system, which means that a variable, declared with no type may be inferred by TypeScript based on its value.

  • Object oriented programming – TypeScript supports object-oriented programming concepts like classes, inheritance, etc.

  • Compile time checks – JavaScript is an interpreted programming language. There is no compilation involved. Hence, the errors get caught during the runtime. Since TypeScript compiles into JavaScript, errors get reported during the compile time rather than the runtime.

  • Code editor support – IDEs or code editors like VS Code support autocomplete for a TypeScript codebase. They also provide inline documentation and highlight the errors.

  • Use existing packages – You might want to use an npm package that is written in JavaScript. Since TypeScript is a superset of JavaScript, you can import and use that package. Moreover, the TypeScript community creates and maintains type definitions for popular packages that can be utilized in your project. You can learn more about it here.

What is the best way to learn TypeScript?

TypeScript comes with tons of features, and learning and implementing them all together might get overwhelming. I started learning TypeScript by refactoring my JavaScript codebase to TypeScript one line at a time. This helped me to migrate my codebase to TypeScript with minimal effort and helped me dive deeper into the concepts.

The TypeScript Handbook is a great place to learn about TypeScript. It explains the concepts well and contains relevant examples. The handbook is also regularly updated with new features.

There are also tutorials available that will help you with migrating your JavaScript project to TypeScript or help you learn about DOM manipulation in TypeScript.

The Contentful community members have also created apps and tools that can help generate type declarations for your content types and sync TypeScript with your content model.

If you’re looking for your next TypeScript project, why don’t you create an app for your Contentful space with App Framework? The boilerplate is available in TypeScript, where you can learn or brush up your TypeScript knowledge. Happy type checking!

Top comments (9)

Collapse
 
clay profile image
Clay Ferguson

I have a massive side project (Quarter million lines of code, although a lot of it Java), and for a large project like that there's pretty much no way I'd have the kind of rock solid quality I have without the compiler checks TypeScript is doing.

Collapse
 
peerreynders profile image
peerreynders • Edited

Just one example: Java is not a safe language

Similar arguments can be made about C#, Go, etc. and of course TypeScript.

I'm not saying static analysis is useless but I wince every time the term type safe appears anywhere near TypeScript. TypeScript's capabilities are limited due to its commitment to gradual typing (and runtime safety isn't its job).

In hindsight as a Java and C# developer I felt overconfident in the safety that static analysis provided, something which I only realized once I exposed myself to languages like OCaml and Haskell which don't rely on classes to emulate a rich type system.

Also TypeScript brings with it a pronounced asymmetry of effort beyond what was previously observed with other mainstream statically typed languages.

TypeScript is easy to adopt when you're essentially gluing together various pre-existing products to achieve some higher level functionality but once you stray into the "from scratch but somewhat general" territory for any part, you have to deal with the learning curve of type level programming.

In the end even with TypeScript I feel I have to constantly "watch my back"; at least in comparison to something like Rust.

Overall I find that benefits of TypeScript are often overhyped (at least in terms of safety) while the costs are usually downplayed.

Because of this I treat TypeScript more like a "Type Linter" rather than a full blown programming language.

Collapse
 
clay profile image
Clay Ferguson • Edited

What I generally mean by "Type Safety" in TypeScript is that if I opened one of my TS files at random and put a typo in any variable at all, the compiler would catch it, and that's what I want. If I pass the wrong argument to a method, or try to access a property that is not on an object, again TS compiler catches it.

It's up to the developer (with TS) to be sure to use types for all variables (objects) but if you simply do that you do get what I can correctly call "100% TypeSafety" because I explained how I define what that safety means and 100% of my code is type safe in the way I just described.

Thread Thread
 
peerreynders profile image
peerreynders • Edited

Current rendition from the great sink of human knowledge:

"type safety and type soundness are the extent to which a programming language discourages or prevents type errors."

"A type error is an unintended condition which might manifest in multiple stages of a program's development. Thus a facility for detection of the error is needed in the type system."

Interestingly:
"TypeScript’s type system allows certain operations that can’t be known at compile-time to be safe. When a type system has this property, it is said to not be “sound”. The places where TypeScript allows unsound behavior were carefully considered, and throughout this document we’ll explain where these happen and the motivating scenarios behind them."

Static analysis will catch typos but ultimately that has nothing to do with "type safety".

And if anything, ubiqutous langauge has taught us that we need to stick to previously agreed to meanings of existing terms in order to communicate effectively.

Thread Thread
 
clay profile image
Clay Ferguson

I think language terms derive their meaning based on context. For example, I can say C++ has "classes" and I can also say TypeScript/JS has "classes". Similarly the term "Type Safety" has a generally well understood meaning across the industry and across languages, although each language has it's own nuances.

Thread Thread
 
peerreynders profile image
peerreynders

I think language terms derive their meaning based on context.

…and switching contexts leads to expectations no being met.

Going from C++ to TypeScript means losing multiple inheritance and using interface instead of abstract classes (even though TypeScript supports those). Going further into JavaScript where "classes are a template for creating objects"; objects can be augmented during runtime to adopt behaviour that conflicts with the notion of "class membership". Meanwhile custom elements cannot be created with mere user-defined constructor functions (JS classes are not “just syntactic sugar”) because the native DOM implementation uses native classes.

As to typos.

Those were already caught with use strict which has been available since 2012. Of course that was runtime check. So language aware editors have been catching those for quite some time without typechecking and linting tools have also been catching those for a while via static analysis.

Typos will be caught during type checking; that's just something that has to be already satisfied before type checking can even start.

A large segment of the TypeScript community advocates not specifying function return types; specifying only parameter types specifies the function type only half-way. This seems to reflect a rather casual attitude towards type safety (as the consumer of the return value may also rely on type inference). For example, Rust also has type inference but requires function return types as those are part of the full contract; function return types are valuable typing check points.

And just recently I ran into an error that I didn't resolve by correcting types but by enabling TypeScript's strict mode.

I would argue that the driver behind TypeScript's adoption is mostly convenience (unless you're a library maintainer) rather than safety.

Thread Thread
 
clay profile image
Clay Ferguson

Glad your a fan of Type Safety! Every experienced developer is. Thanks for the primer on C++, but my first decade as a developer was C++, so I was aware. My second two decades were Java and WebApps.

I love how TS checks every line of my code for perfect compile-time correctness, but I also use a linter to catch even a rogue space at the end of a line, or whatever else which isn't even an error. lol.

If you get bored check out my project here: quanta.wiki/tab/feed

Collapse
 
bwca profile image
Volodymyr Yepishev

Typescript is almost the ES4 we never got :)

Collapse
 
decker67 profile image
decker

Happy type checking!
Yes that's the outcome. You are more type checking than programming.,😂