Typescript logo

What is TypeScript: A Beginner’s Guide

December 16, 2022
Emmanuel Uchenna
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Introduction

There is no better way to write JavaScript than using TypeScript. TypeScript is a superset of JavaScript language. TypeScript has gained increasing popularity over the past years to become the most popular programming language in 2021 according to a 2022 State of Software Delivery report by CircleCI.

https://i.imgur.com/srsbdvx.png
https://i.imgur.com/srsbdvx.png

Image source – 2022 State of Software Delivery report by CircleCI

What is TypeScript?

The official Typescript website defines TypeScript as:

TypeScript is JavaScript with syntax for types. It is a strongly typed programming language that builds on JavaScript language, giving you better tooling at any scale.

typescript text
https://i.imgur.com/uQO82Ow.png

Basics of the Language

To use TypeScript, you will first need to install it on your system. This can typically be done through a package manager like npm, which is included with Node.js. Once TypeScript is installed, you can start using it by creating a TypeScript file with a .ts extension. This file can then be compiled into JavaScript using the TypeScript compiler, which will generate a corresponding .js file that can be run in any JavaScript environment.

In this tutorial, you will learn more about TypeScript, its features, and why you should choose TypeScript instead of using Vanilla JavaScript

Statistical Reports

Programming languages by usage and satisfaction were ranked according to the Jamstack Community Survey 2022, which revealed that TypeScript usage continued to grow quickly, reaching 67% in 2022. Additionally, 21% of developers stated that TypeScript is their primary language.

In conclusion, a lot of JavaScript developers are switching to TypeScript at the moment.

statistics about Typescript
https://i.imgur.com/rQ7ZCzw.png

Why Should You Use TypeScript?

TypeScript language is your go-to language because it provides the developer with type definitions, among other benefits of a programming language. Using the TypeScript language boosts your confidence and productivity as a developer because TypeScript helps you spot errors locally, therefore reducing the time required to deliver efficient code, code formatting, produce better software.

More specifically, developers are porting to TypeScript because of its developer-friendly features. TypeScript provides the programmer with extra features that are not readily available in vanilla JavaScript. The extra features include:

Extra Features

  • Static typing: Because JavaScript is a dynamically typed language, variable types can change within a program. Microsoft is proposing optional static typing in JavaScript, according to a report. In contrast, TypeScript has static typing. Static typing simply means that the type of a variable cannot change throughout the program. This leads to a reduction in the number of bugs. The below example demonstrates the benefit of using static typing:
  // JavaScript
  let age = "Ninety two";
  age = 92; // age has changed type from a string to a number - no problem
  // TypeScript
  let age: string = "Ninety two";
  age = 92; // ERROR - age cannot change from string to number


  • Auto-complete: Code completion, Intellisense, and suggestions for TypeScript are supported by all popular code editors, including VS Code, SublimeText, and WebStorm. You as a developer will benefit more generally from these features.
  • Object Oriented Programming (OOP) Support: TypeScript supports Object Oriented Programming (OOP). The OOP principles supported by TypeScript include classes, interfaces, and inheritance; also, it supports other language features making it a great choice for building large and complex applications.
  • Decorators: TypeScript introduced decorators available as an experimental feature in TypeScript. According to Saul Mirone, decorators make the world of TypeScript better. They let you, as a developer, implement a proxy pattern, thereby reducing the amount of code duplication.function simpleDecorator() { console.log('---hi I am a decorator---') } @simpleDecorator class A {} The above code logs —hi I am a decorator— in the console.According to the TypeScript official documentation, decorators as at the time of writing this article, are still an experimental feature. However, as a developer, you may start using them in your code.You must enable experimental support for decorators to use the decorators. To do this, you can either enable the experimentalDecorators compiler option via the command line or in your tsconfig.json:Command Line:tsc --target ES5 --experimentalDecorators tsconfig.json:{ "compilerOptions": { "target": "ES5", "experimentalDecorators": true } }

These extra features enable you to write better, more scalable JavaScript code. Ultimately, your TypeScript code is compiled into vanilla JavaScript using the In this tutorial, you will learn more about TypeScript, its features, and why you should choose TypeScript instead of using Vanilla JavaScript.

Advantages of Using TypeScript

The TypeScript language is a superset of JavaScript. It is preferred over JavaScript because of the highlighted points.

These are a few of the reasons, as a developer, you may consider porting to TypeScript:

Static typing:

TypeScript is statically typed, which means that variables have a specific type and the type of a variable cannot change later on in your code. This means that variables and functions must be declared with a specific type. This can improve code readability and make it easier to understand the intended behavior of the code. Moreover, it allows checking of errors before runtime, that is while compiling. This is another area where TypeScript adds support for loosely typed programming language, JavaScript. With TLS (the TypeScript Language Service mentioned above), TypeScript has an optional static typing and type inference system that can infer undeclared variables. Thus, TypeScript adds support by mitigating type errors during development.

Take a look at the example below:

// TypeScript
// Declare the variable "name" with the type "string"
let name: string = "Eunit";
// Attempt to assign a number value to the "name" variable, which will cause a type error
name = 99; // TypeError: Type '99' is not assignable to type 'string'


IntelliSense:

TypeScript includes built-in support for IntelliSense, which is a feature of many code editors like VS Code that provides auto-completion and type information as you type. This can help you write code more quickly and accurately. It is a feature of many code editors that provides suggestions for code completion based on the context of the code being written. The following code demonstrates how intellisense can be used in Typescript:

// Declare a variable "name" with the type "string"
let name: string;
// Start typing the variable "name"
name
// Intellisense will provide suggestions based on the type of the "name" variable
// For example, it may suggest methods like "toUpperCase()" or "toLowerCase()"
name.


Classes and interfaces:

TypeScript is an object-oriented programming language that supports object-oriented programming concepts like classes and interfaces, which can help you write more organized and reusable code.

A class is a blueprint for creating objects with specific properties and methods. Here is an example of a class:

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
    move(dx: number, dy: number) {
        this.x += dx;
        this.y += dy;
    }
}


In the example above, the Point class has two properties, x and y, which represent the coordinates of the point on a two-dimensional plane. The Point class also has a move method, which allows you to move the point by a certain amount in the x and y directions.

An interface, on the other hand, is a way of defining a contract for a class or a set of objects. An interface defines a set of properties and methods that a class must implement to comply with the contract.

Easier to maintain:

Because TypeScript provides strict typing and other features such as OOP that can help catch errors early on, it can make it easier to maintain and modify your codebase over time even if it is a large codebase.

Better performance:

TypeScript code can be compiled down to JavaScript, which can help improve the performance of your applications. Overall, the use of TypeScript can lead to more efficient and reliable code. This can save time and effort for developers. When building user interfaces, TypeScript can be combined with a UI library like ReactJS to create production-grade applications.

What is a TypeScript Compiler?

TypeScript codes cannot be interpreted directly by your browser. It needs to be compiled down to JavaScript. This is where the TypeScript compiler comes into play. The TypeScript compiler is a command-line tool that converts TypeScript code into plain JavaScript code that can be run in a web browser or other JavaScript environments. It is called the “TypeScript compiler” because it compiles TypeScript code into JavaScript code.

How the Typescript Compiler Works

To use the TypeScript compiler, you first need to install it on your computer. This can be done using npm, the package manager for JavaScript, by running the following command:

npm install -g typescript

Once the TypeScript compiler is installed, you can compile TypeScript code by running the following command, where “validators.ts” is the name of the TypeScript file you want to compile:

tsc validators.ts

This will produce a file named “validators.js” that contains the compiled JavaScript code. You can then run this JavaScript code in a web browser or another JavaScript environment.

The TypeScript compiler has several additional options that can be used to customize the way it compiles TypeScript code. For example, you can specify the JavaScript target version, enable or disable type checking, and control the level of error reporting.

https://i.imgur.com/1EHlGp0.png
https://i.imgur.com/1EHlGp0.png

Overall, the TypeScript compiler is an important tool for anyone working with the TypeScript language, as it allows you to compile your TypeScript code into plain JavaScript that can be run in a web browser or other JavaScript environment.

What is TypeScript Code Syntax

One of the key features of TypeScript is its type system. This allows developers to specify the type of a variable, function, or object, which can help catch errors early on in the development process. For example, in TypeScript you can define a variable with a specific type like this:

let orgName: string = "CopyCat";

In the code above, the orgName variable is declared with the type string, which means that it can only hold string values. If you try to assign a value of a different type, like a number, to this variable, TypeScript will raise an error.

Another important feature of TypeScript is its support for interfaces. An interface defines a contract that specifies the shape of an object. This means that it specifies the properties and methods that an object should have, along with their types.

For example, you could define an interface for a user object like this:

interface User {
  firstName: string;
  lastName: string;
  age: number;
  getFullName(): string;
}

This interface defines a User object that has four properties: firstName, lastName, age, and getFullName. The getFullName method is a function that returns a string.

To implement this interface, you would create a class that has the same properties and methods defined in the interface. For example:

class MyUser implements User {
  firstName: string;
  lastName: string;
  age: number;

  constructor(firstName: string, lastName: string, age: number) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  getFullName() {
    return this.firstName + " " + this.lastName;
  }
}


In this example, the MyUser class implements the User interface. This means that it has the same properties and methods defined in the interface.

Features of a TypeScript Project

In this section, we will take a closer look at some of the key features of a TypeScript project.

  • TypeScript files use .tsx, and .ts instead of .jsx, or .js file for create-react-app.
  • For example, you have App.tsx, and index.ts in TypeScript files for a React-TypeScript application.
  • A tsconfig.json file is required for each TypeScript-based project. It defines the project’s root files as well as the compiler parameters needed to compile it. As you work on the project, you will make regular changes to this file.

What are TypeScript Interfaces and Classes in TypeScript

An interface in TypeScript is a syntactical contract that defines the shape of an object. It specifies the properties, methods, and events that an object should have, without providing any implementation details. Interfaces are used to define a common structure that can be implemented by one or more classes.

On the other hand, a class in TypeScript is a blueprint for creating objects. It defines the properties, methods, and events that a particular type of object should have. Classes can also define constructor functions, which are used to initialize the object’s properties.

Difference between TypeScript and JavaScript

Both TypeScript and JavaScript are programming languages, although they serve different purposes. JavaScript is a scripting language that is commonly used for front-end web development and is executed in the user’s web browser.

TypeScript, on the other hand, is an object-oriented programming language that is closely related to -but is a superset of JavaScript, which means that it has all of JavaScript’s features as well as some new ones. It is commonly used for big, complicated projects and is compiled into JavaScript before being launched in a web browser.

What are Some TypeScript Competitors?

Some of the main competitors to TypeScript include languages such as:

JavaScript: JavaScript is considered the best alternative to TypeScript because they are closely related languages. JavaScript is faster than TypeScript because it does not need to be compiled and is client-side. Additionally, JavaScript is considered a more versatile scripting language than TypeScript.

Java: This is a popular programming language that is used for building a wide range of applications, including web, mobile, and desktop apps. It is a statically-typed language, which means that variables and other data types must be explicitly declared before they can be used in the code.

C#: C# was developed by Microsoft. It is similar to Java in many ways and is often used for building web, desktop, and mobile applications. Like Java, C# is a statically-typed language.

Kotlin: This is a relatively new programming language that was developed by JetBrains. It is fully interoperable with Java, which means that you can use Kotlin code alongside Java code in the same project. It is a statically-typed language that offers many of the same features as Typescripts’, such as type inference and type safety.

Swift: This is a programming language that was developed by Apple for building apps for their platforms, such as iOS, macOS, watchOS, and tvOS. It is a statically-typed language that is designed to be easy to read and write and offers many of the same features as Typescripts’, such as type inference and type safety.

Ultimately, the choice of which programming language to use will depend on the specific requirements of your project, as well as your personal preferences and experience.

Conclusion

In this article, you read an exhaustive post about TypeScript, its features, and why developers choose it over its subset, JavaScript. You read that TypeScript has become the most popular programming language, according to a report by CircleCI.

You also learned that TypeScript is a superset of JavaScript, which means that all JavaScript code is also TypeScript code. The language is popular because it provides software developers with type definitions and strong typing, it is great for pointing out errors beforehand, among other features, which can help to reduce the number of errors in code. Additionally, TypeScript has many other useful features, such as auto-complete and type-checking, that are not available in vanilla JavaScript.

Interesting Reads From Our Blog

Videos Examples About TypeScript

About CopyCat

Are you tired of manually coding your UI designs? CopyCat is a revolutionary tool that allows you to easily convert your UI designs into functional code in seconds. With CopyCat, you can bring your designs to life without the tedious and time-consuming process of coding by hand. Simply upload your design and let CopyCat do the rest. Try CopyCat today and see the difference for yourself!

Related Articles

  • React.js

    What to Read When Using React Typescript In Your App

    Introduction These days, businesses are migrating their applications and digital product from plain ol' Javascript to Typescript. Why? Well, we could liken Typescript to Javascript with superpowers. How? We'll find out as we progress. Before we go into details, check…

    October 1, 2022
  • React.js

    React Strict Mode: A Guide on Using it in your Application

    Introduction React Strict Mode is a developer tool that has been around in React from version 16.3. But, if you are like me, you might be seeing it in your index.js file without giving it a thought about why it has been there (if…

    September 14, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code