search
HomeWeb Front-endJS TutorialBuilding with TypeScript: A Lego-Based Guide

TypeScript: The smooth transition from JavaScript to TypeScript is like upgrading your Lego building process!

Building with TypeScript: A Lego-Based Guide

“Do what you can, use what you have” – this is one of my mottos. This sentence also reflects part of the growth mindset. Most of us front-end or JavaScript developers have already started or completely migrated to TypeScript. But some people may still have difficulty understanding the concepts, or switching their mindset from JavaScript to TypeScript. To solve this problem, we're going to use one of my favorite tools: Legos. Let’s start here: “Think of JavaScript as a basic set of Lego bricks that you can build freely; TypeScript is the same set of bricks, but with detailed instructions and quality control checks.” For a more in-depth discussion of TypeScript, you can refer to here , here , and this video . This guide aims to show how each JavaScript concept translates to TypeScript, using Lego analogies to help you understand the concepts more easily.

Variable Scope and Hoisting: Building a Room

Building with TypeScript: A Lego-Based Guide

Concept definition

Variable scope refers to the context in which variables can be accessed and used in a program. There are two main types of scope: local scope and global scope. A variable declared outside any function is in global scope, which means it can be accessed and modified anywhere in the code. On the other hand, variables declared inside a function are in local scope and can only be accessed within that function. JavaScript uses the var, let, and const keywords to declare variables, and each keyword has a different impact on the scope. Variables declared with let and const are block scoped, which means they can only be accessed within the nearest enclosing block {}. In contrast, var is function-scoped, making it available throughout the function in which it is declared. A clear understanding of variable scope helps avoid problems such as variable name conflicts and unexpected side effects in JavaScript programs.

Hoisting is the act of moving variable and function declarations to the top of their containing scope before the code is executed (compilation phase). This means that variables and functions can be used before they are declared. Function declarations are fully hoisted, allowing them to be called even before they are defined in the code. However, variables declared with var are hoisted but not initialized to their initial value, so accessing them before assignment will result in undefined. Variables declared with let and const are also hoisted but not initialized, which would result in ReferenceError if accessed before declaration. Understanding promotion helps developers avoid common pitfalls by constructing variable and function declarations correctly.

Lego analogy

Think of scopes as different Lego rooms:

  • Global scope: All builders can access the shared living room of the building blocks.
  • Function scope: personal building table.
  • Block Scope: Build a specific area of ​​the table.

JavaScript implementation

// 全局搭建房间
const globalBricks = "每个人都可以使用这些";
function buildSection() {
    // 个人搭建桌
    var tableBricks = "仅供此搭建者使用";

    if (true) {
        // 特定区域
        let sectionBricks = "仅供此部分使用";
    }
}

TypeScript Evolution

// 为我们的搭建房间添加类型安全
type BrickType = "regular" | "special" | "rare";
const globalBricks: BrickType = "regular";

function buildSection(): void {
    // TypeScript确保我们只使用有效的积木类型
    const tableBricks: BrickType = "special";

    if (true) {
        // TypeScript阻止在此块之外使用sectionBricks
        let sectionBricks: BrickType = "rare";
    }
}

// 真实世界的例子:配置管理
interface AppConfig {
    readonly apiKey: string;
    environment: "dev" | "prod";
    features: Set<string>;
}

const config: AppConfig = {
    apiKey: "secret",
    environment: "dev",
    features: new Set(["feature1", "feature2"])
};

Functions and Closures: Building Instructions

Building with TypeScript: A Lego-Based Guide

Concept definition

Functions are reusable blocks of code designed to perform a specific task. This enhances modularity and code efficiency. They can be defined using the function keyword, followed by a name, brackets () and a block of code enclosed in curly brackets {}. Arguments can be passed into a function within parentheses or braces, which act as placeholders for the values ​​provided when the function is called. JavaScript also supports anonymous functions (without names) and arrow functions (providing a cleaner syntax). Functions can use the return statement to return a value, or perform operations that do not return a value. Additionally, functions in JavaScript are first-class objects, which means they can be assigned to variables, passed as arguments, and returned from other functions, thus enabling the functional programming pattern.

Closures are a powerful feature that allow a function to remember and access its lexical scope even if the function executes outside that scope. Closures can be created when a function is defined inside a function and references variables in the outer function. Even after the outer function has finished executing, the inner function can still access these variables. This feature is useful for data encapsulation and maintaining state in environments such as event handlers or callbacks. Closures support patterns such as private variables, where functions can expose specific behavior while hiding implementation details.

Lego analogy

  • Functions are like building instructions.
  • Parameters are like required building blocks.
  • The return value is like a completed structure.
  • A closure is like a sealed building kit with a few permanently included building blocks.

JavaScript implementation

function buildHouse(floors, color) {
    const foundation = "concrete";

    return function addRoof(roofStyle) {
        return `${color} house with ${floors} floors and ${roofStyle} roof on ${foundation}`;
    };
}

TypeScript Evolution

// 带有类型的基本函数
interface House {
    floors: number;
    color: string;
    roofStyle: string;
    foundation: string;
}

// 为我们的搭建者添加类型安全
function buildHouse(
    floors: number,
    color: string
): (roofStyle: string) => House {
    const foundation = "concrete";

    return (roofStyle: string): House => ({
        floors,
        color,
        roofStyle,
        foundation
    });
}

// 真实世界的例子:组件工厂
interface ComponentProps {
    id: string;
    style?: React.CSSProperties;
    children?: React.ReactNode;
}

function createComponent<T extends ComponentProps>(
    baseProps: T
): (additionalProps: Partial<T>) => React.FC<T> {
    return (additionalProps) => {
        // 组件实现
        return (props) => <div></div>;
    };
}

Objects and Prototypes: Building Tips

Building with TypeScript: A Lego-Based Guide

Concept definition

Objects in JavaScript are basic data structures that serve as containers for related data and functionality. They consist of key-value pairs, where each key (property) maps to a value, which can be any valid JavaScript type, including functions (methods). Objects can be created in several ways:

  • Object literal: const obj = {}
  • Constructor: new Object()
  • Object.create()Method

The prototype system is JavaScript’s built-in inheritance mechanism. Every object has an internal link to another object, called its prototype. When trying to access a property that doesn't exist on an object, JavaScript automatically looks for it in its prototype chain. This object chain continues until it reaches an object with the null prototype, usually Object.prototype. Understanding prototypes is critical to:

  • Implement inheritance
  • Sharing methods between instances
  • Manage memory efficiency
  • Build object hierarchy

Lego analogy

Think of objects and prototypes like this:

  • Objects are like dedicated LEGO kits with their own unique bricks and instructions.
  • A prototype is like a master template that multiple kits can reference.
  • Inheritance is like having a basic suite from which more advanced suites can be built.
  • Properties are like specific building blocks in each kit.
  • Methods are like special building tips included in each kit.

JavaScript implementation

// 全局搭建房间
const globalBricks = "每个人都可以使用这些";
function buildSection() {
    // 个人搭建桌
    var tableBricks = "仅供此搭建者使用";

    if (true) {
        // 特定区域
        let sectionBricks = "仅供此部分使用";
    }
}

TypeScript Evolution

// 为我们的搭建房间添加类型安全
type BrickType = "regular" | "special" | "rare";
const globalBricks: BrickType = "regular";

function buildSection(): void {
    // TypeScript确保我们只使用有效的积木类型
    const tableBricks: BrickType = "special";

    if (true) {
        // TypeScript阻止在此块之外使用sectionBricks
        let sectionBricks: BrickType = "rare";
    }
}

// 真实世界的例子:配置管理
interface AppConfig {
    readonly apiKey: string;
    environment: "dev" | "prod";
    features: Set<string>;
}

const config: AppConfig = {
    apiKey: "secret",
    environment: "dev",
    features: new Set(["feature1", "feature2"])
};

Asynchronous Programming: Building a Team

Building with TypeScript: A Lego-Based Guide

Concept definition

Asynchronous functions and programming

Asynchronous functions are a special function type in JavaScript that provide an elegant way to handle asynchronous operations. When declared with the async keyword, these functions automatically return a Promise and enable the use of the await keyword in their body. The await operator pauses the execution of a function until the Promise is resolved or rejected, allowing asynchronous code to be written in a more synchronous and readable style. This syntax effectively reduces the complexity of callbacks and eliminates the need for nested Promise chains. For example, in async function fetchData() { const response = await fetch(url); }, the function waits for the fetch operation to complete before continuing execution, making the behavior of the code more predictable while ensuring that the main thread remains unblocked. This pattern is particularly useful when dealing with multiple asynchronous operations that depend on each other, because it allows developers to write code that clearly expresses the order of operations without sacrificing performance.

Promise

Promise represents a value that may be available now, available in the future, or never available. It is an object with three possible states: Pending, Completed, or Rejected. It is used to handle asynchronous operations. Promises have methods such as .then(), .catch() and .finally() for chaining actions based on the result. This makes them a powerful alternative to nested callbacks, improving code readability and error handling.

Lego analogy

  • Asynchronous functions are like team members working on different parts.
  • Promise is like an agreement to deliver the completed part.

JavaScript implementation

// 全局搭建房间
const globalBricks = "每个人都可以使用这些";
function buildSection() {
    // 个人搭建桌
    var tableBricks = "仅供此搭建者使用";

    if (true) {
        // 特定区域
        let sectionBricks = "仅供此部分使用";
    }
}

TypeScript Evolution

// 为我们的搭建房间添加类型安全
type BrickType = "regular" | "special" | "rare";
const globalBricks: BrickType = "regular";

function buildSection(): void {
    // TypeScript确保我们只使用有效的积木类型
    const tableBricks: BrickType = "special";

    if (true) {
        // TypeScript阻止在此块之外使用sectionBricks
        let sectionBricks: BrickType = "rare";
    }
}

// 真实世界的例子:配置管理
interface AppConfig {
    readonly apiKey: string;
    environment: "dev" | "prod";
    features: Set<string>;
}

const config: AppConfig = {
    apiKey: "secret",
    environment: "dev",
    features: new Set(["feature1", "feature2"])
};

Modern Features: Advanced Building Techniques

Building with TypeScript: A Lego-Based Guide

Concept definition

Deconstruction

This is a neat way to extract values ​​from an array or properties from an object into different variables. Array destructuring uses square brackets [], while object destructuring uses curly brackets {}. This syntax reduces the need for duplicate code by unpacking values ​​directly into variables, making it easier to handle complex data structures. For example, const [a, b] = [1, 2] assigns 1 to a and 2 to b, while const { name } = person extracts the name attribute from the person object.

Expand operator

The spread operator is represented by three dots (...). It allows iterable objects such as arrays or objects to be extended where multiple elements or key-value pairs are required. It can be used to copy, combine, or pass array elements as function arguments. For example, const arr = [1, 2, ...anotherArray].

Optional chain

Optional chains are represented by ?.. It provides a safe way to access deeply nested object properties without causing errors when the property is undefined or null. If the reference is nullish, it short-circuits and returns undefined immediately. For example, user?.address?.street checks if user and address exist before accessing street. This syntax prevents runtime errors and makes working with nested data structures cleaner and less error-prone, especially in APIs or data that relies on user input.

Lego analogy

  • Deconstruction is like sorting building blocks into containers.
  • The spread operator is like copying building blocks between suites.
  • Optional chaining is like checking if a block exists before using it.

JavaScript implementation

function buildHouse(floors, color) {
    const foundation = "concrete";

    return function addRoof(roofStyle) {
        return `${color} house with ${floors} floors and ${roofStyle} roof on ${foundation}`;
    };
}

TypeScript Evolution

// 带有类型的基本函数
interface House {
    floors: number;
    color: string;
    roofStyle: string;
    foundation: string;
}

// 为我们的搭建者添加类型安全
function buildHouse(
    floors: number,
    color: string
): (roofStyle: string) => House {
    const foundation = "concrete";

    return (roofStyle: string): House => ({
        floors,
        color,
        roofStyle,
        foundation
    });
}

// 真实世界的例子:组件工厂
interface ComponentProps {
    id: string;
    style?: React.CSSProperties;
    children?: React.ReactNode;
}

function createComponent<T extends ComponentProps>(
    baseProps: T
): (additionalProps: Partial<T>) => React.FC<T> {
    return (additionalProps) => {
        // 组件实现
        return (props) => <div></div>;
    };
}

Summary

Building with TypeScript: A Lego-Based Guide

The transition from JavaScript to TypeScript is like upgrading your Lego building process:

  1. JavaScript (basic construction):

    • Free-form construction
    • Flexible use of building blocks
    • Runtime error detection
  2. TypeScript (professionally built):

    • Detailed and specific instructions
    • Brick Compatibility Check
    • Error prevention before construction

Key transition tips:

  1. Start with basic type annotations.
  2. Add interfaces and type definitions gradually.
  3. Use the compiler to catch errors early.
  4. Use type inference whenever possible.
  5. Strict null checking and other compiler options are gradually added.

Remember: TypeScript builds on your JavaScript knowledge, adding security and clarity, rather than changing the fundamental building process. That said, my advice is still... learn JavaScript first, then learn TypeScript.

References

    Retrieved January 12, 2025, from
  • https://www.php.cn/link/84b184211c5d929d9435a371eb505cad Mozilla. (n.d.). Variables — JavaScript
  • . MDN Web Docs. Retrieved January 14, 2025, from
  • https://www.php.cn/link/646e69d6e105d351e4e31a2e02a69b0e

The above is the detailed content of Building with TypeScript: A Lego-Based 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.