Home >Web Front-end >JS Tutorial >TypeScript Fundamentals: A Beginner&#s Guide (✅

TypeScript Fundamentals: A Beginner&#s Guide (✅

Patricia Arquette
Patricia ArquetteOriginal
2025-01-07 12:38:40360browse

TypeScript Fundamentals: A Beginner

TypeScript has caused endless debates among developers. Some see it as a bureaucratic roadblock to the freedom of JavaScript, while others hail it as a beacon of light in the trenches of loosely typed code. Love it or hate it, TypeScript is here to stay — and once you get to know it, you might just find it’s not a burden but a blessing for your projects.

In this series we will explore TypeScript and cover the basics -- as well as some tricks and troubleshooting tips.

1. Introduction

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. In simpler terms, it’s JavaScript with extra features that help you catch errors early and write better, more maintainable code.

Think of TypeScript as a friendly assistant who double-checks your work before you submit it. It lets you:

  • Spot errors while you’re coding, not after you’ve deployed.
  • Write code that’s easier to read and understand.
  • Scale your projects without losing track of how things connect.

Why Use TypeScript?

Let’s get practical. Why should you care about TypeScript when JavaScript already works?

Real Benefits:

  1. Catch Errors Early: Avoid common pitfalls, like passing the wrong data type to a function.
   function greet(name: string) {
     return `Hello, ${name}!`;
   }
   greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
  1. Autocompletion & Documentation: Modern editors (like VS Code) provide rich autocomplete suggestions and documentation as you type.

  2. Code Scalability: TypeScript’s features shine in larger projects where maintaining consistency is key.

  3. Improved Team Collaboration: Clear types make it easier for team members to understand your code at a glance.

I have found TypeScript to be particularly helpful for planning out bigger apps; understanding what types of data I will be dealing with and what data my functions take/return.

Prerequisites

Before diving in, ensure you have basic JavaScript knowledge. You should be familiar with:

  • Variables and data types (e.g., let, const, string, number)
  • Functions
  • Arrays and objects

If you’re not confident yet, take some time to review JavaScript basics.


2. Setting Up Your Environment

Installing TypeScript

TypeScript is a tool that requires installation to get started. With just a few steps, you can prepare your environment to begin coding in TypeScript. Here’s how to do it:

To start using TypeScript, you’ll need Node.js installed. Once you have that:

  1. Install TypeScript globally:
   function greet(name: string) {
     return `Hello, ${name}!`;
   }
   greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
  1. Verify the installation:
   npm install -g typescript

Setting Up VS Code

VS Code is one of the most popular editors for TypeScript development. It provides a range of features and extensions that make coding easier and more efficient. Let’s set it up:

VS Code is the go-to editor for TypeScript developers. Here’s how to set it up:

  1. Install VS Code: Download here
  2. Add these helpful extensions:
    • ESLint: For linting your TypeScript code.
    • Prettier: For consistent code formatting.
    • TypeScript Hero: For improved productivity.

Creating Your First TypeScript Project

Getting hands-on is the best way to learn TypeScript. This section guides you through setting up your first project, from creating files to running your code.

  1. Create a new folder for your project and navigate into it:
   tsc --version
  1. Initialize a new project:
   mkdir typescript-starter
   cd typescript-starter
  1. Add TypeScript:
   npm init -y
  1. Create a tsconfig.json file:
   npm install --save-dev typescript
  1. Write your first TypeScript file:
   npx tsc --init
  1. Compile and run:
   echo "console.log('Hello, TypeScript!');" > index.ts

You’ve just written and compiled your first TypeScript program!


3. Basic Types Overview

TypeScript’s power lies in its type system. Let’s explore some basic types:

Primitive Types

Primitive types are the building blocks of TypeScript’s type system. They include basic data types like strings, numbers, and booleans. Here’s a quick look at how to use them:

  1. string:
   npx tsc index.ts
   node index.js
  1. number:
   let name: string = "Alice";
  1. boolean:
   let age: number = 25;

Advanced Types

In addition to primitives, TypeScript supports more complex types like arrays, tuples, and special types like any and unknown. These types make your code flexible while maintaining safety.

  1. Arrays:
   function greet(name: string) {
     return `Hello, ${name}!`;
   }
   greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
  1. Tuples:
   npm install -g typescript
  1. any (use sparingly):
   tsc --version
  1. unknown (safer than any):
   mkdir typescript-starter
   cd typescript-starter
  1. void (functions that return nothing):
   npm init -y
  1. null and undefined:
   npm install --save-dev typescript

4. First Steps with Type Annotations

Type Annotations in TypeScript allow developers to specify the type of a variable, parameter, or function return value. This ensures that the code adheres to a defined structure, making it easier to catch errors during development and maintain consistency throughout the project.

As you write your code as you normally do, take note of the features below that you can integrate

Basic Variable Typing

Set types for your variables so that they are always set to the right thing, and the rest of the app understands what they are.

   npx tsc --init

Function Parameter Typing

Similarly, for functions you can define the types for the arguments, as well define the type for the return.

   echo "console.log('Hello, TypeScript!');" > index.ts

Return Type Annotations

   npx tsc index.ts
   node index.js

Practical Example: User Profile

TypeScript allows you to declare your own types to better structure and enforce rules in your code. By using type or interface, you can define custom types for objects, functions, or even unions. This not only makes your code more robust but also improves readability and consistency in larger projects.

   let name: string = "Alice";

5. Quick Start with Interfaces

Basic Syntax

Interfaces in TypeScript define the structure of objects, ensuring they have specific properties and types. This section shows you how to create and use them:

   let age: number = 25;

Optional Properties

Sometimes, not all properties in an object are required. TypeScript lets you define optional properties in interfaces to handle such cases gracefully.

   let isStudent: boolean = true;

Readonly Properties

Readonly properties are useful when you want to ensure certain values cannot be changed after they are set. Here’s how to use them in interfaces:

   let scores: number[] = [90, 85, 88];

Real-World Example: API Response

Using interfaces to type API responses ensures you handle data from servers safely and effectively. Here’s a practical example:

   let user: [string, number] = ["Alice", 25];

6. Practice Project: Building a Simple Todo List

Practice is key to mastering TypeScript. In this project, you’ll create a simple todo list application that leverages the features you’ve learned so far:

  1. Create a Todo type:
   function greet(name: string) {
     return `Hello, ${name}!`;
   }
   greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
  1. Build a simple array of todos:
   npm install -g typescript
  1. Add some functions to add todos and mark todos as complete:
   tsc --version

7. Next Steps

That's it for now, hope you enjoyed this tutorial. I will be working on some additional tutorials to dig deeper into useful TypeScript features and use cases.

  • Coming Up Next: Deep dive into TypeScript functions and advanced types.
  • Resources:
    • TypeScript Documentation
    • CodeSandbox for practicing TypeScript online.
  • Challenge: Create a TypeScript interface for a blog post and use it to type-check a list of blog posts.

See you next time!

The above is the detailed content of TypeScript Fundamentals: A Beginner&#s Guide (✅. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Tree Shaking in JSNext article:Tree Shaking in JS