Type something to search...
TypeScript 101: Putting ‘seatbelts’ on JavaScript

TypeScript 101: Putting ‘seatbelts’ on JavaScript

Betrayal of JavaScript

JavaScript is the most widely used language in the world, and is a very flexible and easy to write language. However, as the project size grows and becomes more complex, 'flexibility' often becomes a fatal poison that holds developers back.

function addNumbers(a, b) {
return a + b;
}

// Developer's intent: add the numbers 1 and 2 and expect 3
console.log(addNumbers(1, 2)); // 3

// When a string is entered by mistake
console.log(addNumbers("1", "2")); // "12"

In the above code, JavaScript does not emit an error. It simply concatenates the strings "1" and "2" and returns an odd result of "12". This error is discovered only at runtime, and if you are unlucky, it appears as an error on the user's screen after the service is deployed.

TypeScript is a language developed by Microsoft to overcome these limitations of dynamic type languages and catch bugs in advance ‘before executing’ the code.

What is TypeScript?

TypeScript, as its name suggests, is “JavaScript with an added type.” Officially, it is called Superset of JavaScript. It 100% supports the existing JavaScript grammar, but adds the Static Type Checking function on top of it.

Browsers or Node.js environments cannot read TypeScript code directly. Therefore, TypeScript code goes through the process of being translated into pure JavaScript code through a compiler (TSC) before being executed.

What are the benefits of using TypeScript?

  1. Error detection before execution (stability): Errors due to type mismatch are immediately warned with a red line the moment you type code in an editor (VS Code, etc.) or during the build process. You will be greatly relieved from the fear of “Runtime Errors”.
  2. Powerful auto-completion (development productivity): IntelliSense (auto-completion) works very well because the editor knows exactly what properties are in an object, what types of arguments a function receives, and what types it returns.
  3. Specification where the code itself is great (collaboration): When using a complex function written by someone else, you can completely understand how to use it by looking at the declared type without having to look at the entire internal logic.

A sneak peek at core syntax

1. Specify basic type

Specify the type by adding a colon (:) after the variable name or argument.

// Primitive Types
let userName: string = "Jules";
let age: number = 30;
let isDeveloper: boolean = true;

// Array
let skills: string[] = ["React", "TypeScript", "Node.js"];

// Let's buckle up the terrible function we saw above.
function addNumbers(a: number, b: number): number {
return a + b;
}

// Now the editor draws a red line and blocks execution!
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
addNumbers("1", "2");

2. Definition of object type (Interface & Type Alias)

The most confusing thing when developing JavaScript is figuring out what data is contained in an object. In TS, the framework of an object can be designed in advance through the interface or type keyword.

// Define the type of object called User.
interface User {
id: number;
name: string;
email: string;
optionalProfileImage?: string; // If you add ?, it becomes an optional attribute that 'may or may not be present'.
}

// Give the variable the type created above.
const myProfile: User = {
id: 1,
name: "Jules",
email: "[email protected]"
// There is no error even if optionalProfileImage is omitted.
};

//myProfile. The moment you type , the id, name, and email properties are automatically completed!

3. Union Types

Use when you want to allow some degree of flexibility in JavaScript. Specifies that it "can be of type A or B".

// id can be a number or a unique string.
function printId(id: number | string) {
console.log(`Your ID is: ${id}`);
}

printId(101); //OK
printId("UUID-1234"); //OK
printId(true); // Error: boolean not allowed

Conclusion: So should we adopt it?

In conclusion, “unless it is a short-term hackathon or a very light script, it is definitely beneficial to introduce it.”

In the beginning, manually specifying the type for each variable can slow down coding and feel cumbersome. However, as the size of the project grows, the numerous bugs that TypeScript catches in advance and the powerful auto-completion feature compensate for the initial cost by several times more. As of 2024, TypeScript is no longer an option but a 'basic skill' in the front-end and back-end (Node.js) ecosystem.

Related Post

The Complete Guide to Docker: Introduction to and Use of Container Technology for Beginners

The Complete Guide to Docker: Introduction to and Use of Container Technology for Beginners

What is Docker? One of the technologies that has brought about the most innovative changes in the software development and distribution environment in recent years is Docker. Docker is a software

Mastering Kubernetes: Container Orchestration Beyond Docker

Mastering Kubernetes: Container Orchestration Beyond Docker

What is Kubernetes? While Docker revolutionized the creation and management of single containers, Kubernetes (k8s for short) is a 'Container Orchestration' tool that automates the process of depl

The Complete Guide to Git Branching Strategy: From Git Flow to GitHub Flow

The Complete Guide to Git Branching Strategy: From Git Flow to GitHub Flow

A necessity for collaboration, Git branch strategy In software development projects, when multiple developers write code simultaneously, conflicts and confusion inevitably arise. “Who modified th

React vs Vue.js: Guide to Choosing a Front-End Framework in 2024

React vs Vue.js: Guide to Choosing a Front-End Framework in 2024

Front-end war, what is your choice? If you are at all interested in web development, you have probably heard the names 'React' and 'Vue.js' at least once. As the jQuery era comes to an end and th

Website Performance Optimization Strategies: How Loading Speed ​​​​Affects Your Business

Website Performance Optimization Strategies: How Loading Speed ​​​​Affects Your Business

Butterfly effect with 1 second loading speed The patience of not only Koreans, a “fast, quick” people, but also internet users around the world, is getting shorter and shorter. An Amazon study fo

Python Data Analysis Basics: Mastering Pandas Core Functions

Python Data Analysis Basics: Mastering Pandas Core Functions

Excel in the Python data ecosystem, Pandas Why was Python able to become the overwhelming number one language in the fields of data science and machine learning? This is thanks to an excellent ec

Complete CI/CD pipeline automation starting with GitHub Actions

Complete CI/CD pipeline automation starting with GitHub Actions

Escape the nightmare of manual deployment “Okay, now the coding is done! Let’s connect to the server, get git pull, reinstall dependencies, build, kill the existing process, and launch a new pr

Practical guide to developer-prompted engineering in the era of generative AI

Practical guide to developer-prompted engineering in the era of generative AI

Introduction: Why do developers need prompt engineering? In an era where generative AI writes code and fixes bugs, the role of developers is rapidly evolving from simply ‘typing’ code to ‘designi

Front-end ecosystem trends in 2024: What should we learn and prepare for?

Front-end ecosystem trends in 2024: What should we learn and prepare for?

Introduction: The ever-changing front-end ecosystem Among the web development fields, the front-end ecosystem is one where the speed of change is dazzlingly fast. New frameworks and tools are con

Next.js 15+ Deep Dive: Server Component Optimization and Rendering Architecture Evolution

Next.js 15+ Deep Dive: Server Component Optimization and Rendering Architecture Evolution

Introduction: React’s philosophy changes, Next.js and App Router Although React's position in the web development ecosystem is strong, the paradigm of front-end architecture has been undergoing m