DEV Community

Cover image for From JavaScript to TypeScript: Enhance Your Skills and Your Web Development Career
Michael J. Larocca
Michael J. Larocca

Posted on • Originally published at htmlallthethings.com

From JavaScript to TypeScript: Enhance Your Skills and Your Web Development Career

Introduction

As a JavaScript developer, learning TypeScript will enhance your web development skills by gaining the added benefits of static typing, improved tooling, and robust code maintainability. Not only will you become a more versatile developer, but you'll also open doors to a wider range of job opportunities and gain a competitive advantage in the job market!

In this article, tech industry experts Matt Lawrence and Mike Karan will cover TypeScript, including what it is, the basics you should learn, and additional learning resources.

Topics covered in this article include:

  • What TypeScript is

  • Who should learn TypeScript

  • TypeScript Basics


Why JavaScript was made

To better understand what TypeScript is, let's first take a look at what JavaScript is and why it was made.

Before the creation of JavaScript, websites were static, consisting of HTML and CSS only, with no interactivity or dynamic content. So, it was pretty boring. To take webpages to the next level, JavaScript was created by Brendan Eich, making it possible for users to interact with web pages! It's important to note that JavaScript can be read directly by a web browser without being compiled, making it easy to implement on websites.

Brendan Eich developed the initial prototype of JavaScript in just 10 days! 🤯


Why TypeScript was made

Despite its numerous advantages, JavaScript has certain drawbacks. Unlike other coding languages, you do not need to specify variable types in JavaScript (it's a dynamic typing system). This permits variables to change types during runtime, which can result in runtime errors and make code more difficult to maintain as projects increase in complexity.

For example, in Microsoft's VBA coding language (I'm really showing my age with this example 😅), you need to declare a variable type, whereas in JavaScript, you do not:

In VBA, you need to declare a variable type like this:

Dim name As String
Dim age As Integer
name = "Michael Larocca"
age = 48
Enter fullscreen mode Exit fullscreen mode

In JavaScript, you do not need to declare a variable type:

let name = "Michael Larocca";
let age = 48;
Enter fullscreen mode Exit fullscreen mode

Limitations such as these prompted the development of TypeScript by Microsoft in 2012, which aimed to address these concerns and enhance the overall developer experience.

Unlike JavaScript, TypeScript requires transpilation into JavaScript, as it cannot be read directly by a web browser.


💡 Did you know? TypeScript is a superset of JavaScript, which means it includes all features of JavaScript and adds additional features, such as static typing, to make coding more robust and easier to maintain.

Who should learn TypeScript?

So, should you learn TypeScript? Mike explains if you are already earning an income from projects you are creating for clients, it is not necessary for you to learn and incorporate TypeScript in them.

However, If you are learning web development with the intention of being hired, then YES! Not only will you gain a competitive advantage by learning it, but you will also become eligible for a broader range of job opportunities (just check your local job listings to see 📰)!

Mike also advises that students with a background in higher coding languages are also good candidates for learning TypeScript.


How to create a TypeScript project

You can get some practice with TypeScript by creating a React project using Vite and selecting TypeScript when being asked to select a variant. For a beginner-friendly guide, you can follow and code along with my article: How to Create a Local React Environment with Vite

So that you can gain the additional benefits of TypeScript while learning and incorporating the basics, you can disable strict mode. To disable strict mode, set the strict option to false in the tsconfig.json file.

To disable strict mode in TypeScript, modify your tsconfig.json file like this:

{
  "compilerOptions": {
    "strict": false
  }
}
Enter fullscreen mode Exit fullscreen mode

TypeScript basics

😱 Before you hit the panic button because you think you need to become a TypeScript pro in order to qualify for a job, Mike reassures us that we can begin by learning the TypeScript basics and then gradually incorporating more advanced features.

The TypeScript basics include:

  • Static Typing

  • Interfaces and Classes

  • Generics

  • Type Inference


Static Typing

JavaScript uses dynamic typing, which allows the reassignment of a variable's type throughout your program.

For example, if you have a variable for an employee with a number as the variable's type with a value of (12), and then later, it is necessary also to include the employee's area (RED), you can reassign the variable's type to a string so the new value (RED12) would work.

TypeScript uses static typing, which has the ability to set a variable's type when you declare it. Doing so prevents you from changing the variable's type throughout your program.

// JavaScript example (dynamic typing)
let employee = 12;
employee = "RED12";

// TypeScript example (static typing)
let employeeId: number = 12;
// employeeId = "RED12"; // This would cause a type error in TypeScript
Enter fullscreen mode Exit fullscreen mode

TypeScript intersection

TypeScript intersection is a way to combine multiple types into one, allowing a variable or object to have the properties and functionalities of all the combined types. It is denoted by an ampersand (&) between the types.

// Define two types
type EmployeeCode = {
  empCode: string;
};

type EmployeeNumber = {
  empNumber: number;
};

// Intersection type combining EmployeeCode and EmployeeNumber 
type Employee = EmployeeCode & EmployeeNumber ;

// Create an object with the intersection type
const employeeInfo: Employee = {
  empCode: "RED",
  empNumber: 12,
};
Enter fullscreen mode Exit fullscreen mode

TypeScript type any

Not to be used in production code, TypeScript has a type "any" that you can use when you are unsure what the type should be. When you are learning TypeScript, Mike tells us this is an acceptable solution.

let unknownType: any;

unknownType = "Hitchhiker's guide to the galaxy";
unknownType = 42;
unknownType = true;
Enter fullscreen mode Exit fullscreen mode

📝 Note: To allow the usage of the any type in TypeScript set the strict option to false in the tsconfig.json file0


Interfaces and Classes

Mike explains that both Interfaces and Classes originate from object-oriented principles. So, what are these principles? Object-oriented principles are a set of ideas used in programming to organize code around objects that represent real-world things or concepts.

Interfaces

Interfaces define the structure and types of properties that an object should have. Here's an example with a first and last name variable:

interface Wizard {
  firstName: string;
  lastName: string;
}

const dracoMalfoy: Wizard = {
  firstName: "Draco",
  lastName: "Malfoy",
};
Enter fullscreen mode Exit fullscreen mode

You can create another interface, such as one for the sport Quidditch, and have it inherit the information from the Wizard interface.

interface QuidditchPlayer extends Wizard {
  position: string;
  team: string;
}

const quidditchPlayer: QuidditchPlayer = {
  firstName: "Draco",
  lastName: "Malfoy",
  position: "Seeker",
  team: "Slytherin",
};
Enter fullscreen mode Exit fullscreen mode

Classes

Classes can also be used in a similar way to interfaces but with the added functionality of creating constructors and methods.

class Wizard {
  firstName: string;
  lastName: string;

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

  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const dracoMalfoy = new Wizard("Draco", "Malfoy");

class QuidditchPlayer extends Wizard {
  position: string;
  team: string;

  constructor(firstName: string, lastName: string, position: string, team: string) {
    super(firstName, lastName);
    this.position = position;
    this.team = team;
  }

  getPlayerInfo(): string {
    return `${this.getFullName()} is a ${this.position} for the ${this.team} Quidditch team.`;
  }
}

const quidditchPlayer = new QuidditchPlayer("Draco", "Malfoy", "Seeker", "Slytherin");
Enter fullscreen mode Exit fullscreen mode

Generics

Generics are reusable components in TypeScript that can work with different data types while maintaining type safety. They allow you to create flexible and reusable functions or classes without specifying a fixed data type, ensuring code is adaptable and type-safe.

function starTrek<T>(entry: Array<T>): Array<T> {
  return entry;
}

let starTrekData = starTrek<(number | string | boolean)[]>([1701, "Live long and prosper.", true]);
Enter fullscreen mode Exit fullscreen mode

In this code, we have a generic function starTrek that accepts a parameter entry of type Array<T> and returns an array of the same type Array<T>. The <T> denotes the generic type, allowing the function to work with different data types within an array while maintaining type safety.

We then call the function with an array containing a number, a string, and a boolean, demonstrating its flexibility and reusability.

Generics are useful when you do not know the variable types that will be returned, as they allow your code to be adaptable, reusable, and type-safe, ensuring a more robust and maintainable codebase.


💡 Tip: A great way to practice TypeScript is by converting your JavaScript projects to TypeScript!


TypeScript compiling

Unlike JavaScript, TypeScript cannot be directly read by a browser. It needs to be compiled.

The TypeScript Compiler (tsc) is used for this purpose. It checks for type errors and generates JavaScript code that can be executed in the browser. This ensures that your TypeScript code is type-safe and maintainable while still being compatible with web browsers.

To set up and run the TypeScript Compiler (tsc), follow these steps:

  1. Install TypeScript globally using npm: npm install -g typescript

  2. Create a TypeScript file, for example, example.ts

  3. Compile the TypeScript file to JavaScript: tsc example.ts

  4. To set up the TypeScript compiler to run continuously while you're developing, use the --watch flag: tsc example.ts --watch

tsc example.ts --watch
Enter fullscreen mode Exit fullscreen mode

This command will start the TypeScript compiler in watch mode, which means it will continuously monitor the example.ts file for changes and recompile the file whenever it detects any changes, checking for code and type errors in the process.

The tsconfig.json file is a configuration file for the TypeScript compiler. It allows you to customize settings such as target JavaScript version, strict mode, and output directory. To create and configure a tsconfig.json file, follow these steps:

  1. In your project's root directory, create a new file named "tsconfig.json"

  2. Open the tsconfig.json file in your text editor.

  3. Add the following basic configuration:

{
  "compilerOptions": {
    "target": "es5",
    "strict": true,
    "outDir": "./dist"
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Save the file.

In this example, the "target" option is set to "es5, " meaning the TypeScript compiler will generate JavaScript code compatible with the ECMAScript 5 standard. The "strict" option is set to "true," enabling strict type checking for better code quality. The "outDir" option specifies the output directory for the compiled JavaScript files, which in this case is a "dist" folder in the project's root directory.

You can further customize the tsconfig.json file with additional options depending on your project's requirements.


Start learning TypeScript

To start learning TypeScript, follow these actionable steps:

  1. Visit the TypeScript official documentation: https://www.typescriptlang.org/docs/

  2. Take the free Scrimba course by Dylan Israel: https://www.youtube.com/watch?v=Z7O5pQwCmqI&t=21s

  3. Practice by converting your existing JavaScript projects to TypeScript.

  4. Join TypeScript-related forums or communities for support and networking.

By following these steps and utilizing the provided resources, you'll be well on your way to mastering TypeScript and enhancing your web development skills!


HTML All The Things

Be sure to listen to the episode!

Episode 249 Do You Need To Learn TypeScript in 2023?

Be sure to check out HTML All The Things on socials!


Scrimba Discount!

  • Learn to code using Scrimba with their interactive follow-along code editor

  • Join their exclusive discord communities and network to find your first job!

  • Use this URL to get 10% off on all their paid plans: tinyurl.com/ScrimbaHATT

This article contains affiliate links, which means we may receive a commission on any purchases made through these links at no additional cost to you. This helps support our work and allows us to continue providing valuable content. Thank you for your support!


My other HTML All The Things articles


Conclusion

TypeScript was created to address JavaScript's limitations, such as dynamic typing, which can lead to runtime errors and difficult code maintenance.

Learning TypeScript enhances your web development skills by providing static typing, improved tooling, and robust code maintainability. It will also open doors to more job opportunities and give you a competitive advantage!

Begin by learning the basics and gradually incorporate more advanced features to enhance your skills and web development career. TypeScript basics include static typing, interfaces and classes, generics, and type inference.

Remember that TypeScript needs to be compiled because the browser cannot directly read it! To compile TypeScript, use the TypeScript Compiler (tsc) and configure it with a tsconfig.json file.

To get started with learning TypeScript, you can take this FREE Scrimba course taught by tech celebrity Dylan Israel! Intro to Typescript Tutorial with Dylan Israel


Let's connect! I'm active on LinkedIn and Twitter.

selftaughttxg logo

You can read all of my articles on selftaughttxg.com

Top comments (0)