首頁  >  文章  >  web前端  >  TypeScript:JavaScript 的超級英雄斗篷

TypeScript:JavaScript 的超級英雄斗篷

Susan Sarandon
Susan Sarandon原創
2024-10-27 20:45:29947瀏覽

TypeScript: JavaScript

為什麼要新增型別?

想像一下:您正在愉快地使用 JavaScript 進行編碼,突然出現「無法讀取未定義的屬性『名稱』」。呃,我們都去過那裡! TypeScript 就像有一個朋友,可以在這些錯誤發生之前發現它們。

起源故事

JavaScript 就像被蜘蛛咬之前的彼得·帕克 - 潛力巨大,但容易發生意外。 TypeScript 是賦予 JavaScript 超能力的蜘蛛咬傷。它添加了一個類型系統,有助於及早發現錯誤並使您的程式碼更加可靠。

你的第一次 TypeScript 冒險

讓我們從一個簡單的 JavaScript 函數開始,並將其轉換為 TypeScript:

// JavaScript
function greet(name) {
    return "Hello, " + name + "!";
}

現在,讓我們來補充一些 TypeScript 魔法:

// TypeScript
function greet(name: string): string {
    return "Hello, " + name + "!";
}

看到那個:字串嗎? TypeScript 告訴我們「這個函數接受一個字串並回傳一個字串」。現在試試這個:

greet(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'

TypeScript 剛剛讓我們避免了潛在的錯誤! ?

基本類型:你的新超能力

讓我們來探索一些基本的 TypeScript 類型:

// Basic types
let heroName: string = "Spider-Man";
let age: number = 25;
let isAvenger: boolean = true;
let powers: string[] = ["web-slinging", "wall-crawling"];

// Object type
let hero: {
    name: string;
    age: number;
    powers: string[];
} = {
    name: "Spider-Man",
    age: 25,
    powers: ["web-slinging", "wall-crawling"]
};

介面:建立您自己的類型

介面就像是物件的藍圖。它們對於定義資料的形狀非常有用:

interface Hero {
    name: string;
    age: number;
    powers: string[];
    catchPhrase?: string; // Optional property
}

function introduceHero(hero: Hero): void {
    console.log(`I am ${hero.name}, and I'm ${hero.age} years old!`);
    if (hero.catchPhrase) {
        console.log(hero.catchPhrase);
    }
}

const spiderMan: Hero = {
    name: "Spider-Man",
    age: 25,
    powers: ["web-slinging", "wall-crawling"]
};

introduceHero(spiderMan);

類型別名:您的自訂類型

有時您會想建立自己的類型組合:

type PowerLevel = 'rookie' | 'intermediate' | 'expert';

interface Hero {
    name: string;
    powerLevel: PowerLevel;
}

const batman: Hero = {
    name: "Batman",
    powerLevel: "expert" // TypeScript will ensure this is one of the allowed values
};

泛型:終極靈活性

泛型就像通配符,讓您的程式碼更可重複使用:

function createHeroTeam<T>(members: T[]): T[] {
    return [...members];
}

interface Superhero {
    name: string;
    power: string;
}

interface Villain {
    name: string;
    evilPlan: string;
}

const heroes = createHeroTeam<Superhero>([
    { name: "Iron Man", power: "Technology" },
    { name: "Thor", power: "Lightning" }
]);

const villains = createHeroTeam<Villain>([
    { name: "Thanos", evilPlan: "Collect infinity stones" }
]);

真實範例:Todo 應用程式

讓我們使用 TypeScript 建立一個簡單的待辦事項應用程式:

interface Todo {
    id: number;
    title: string;
    completed: boolean;
    dueDate?: Date;
}

class TodoList {
    private todos: Todo[] = [];

    addTodo(title: string, dueDate?: Date): void {
        const todo: Todo = {
            id: Date.now(),
            title,
            completed: false,
            dueDate
        };
        this.todos.push(todo);
    }

    toggleTodo(id: number): void {
        const todo = this.todos.find(t => t.id === id);
        if (todo) {
            todo.completed = !todo.completed;
        }
    }

    getTodos(): Todo[] {
        return this.todos;
    }
}

// Usage
const myTodos = new TodoList();
myTodos.addTodo("Learn TypeScript with baransel.dev");
myTodos.addTodo("Build awesome apps", new Date("2024-10-24"));

TypeScript 與 React

TypeScript 和 React 就像花生醬和果凍。這是一個簡單的例子:

interface Props {
    name: string;
    age: number;
    onSuperPower?: () => void;
}

const HeroCard: React.FC<Props> = ({ name, age, onSuperPower }) => {
    return (
        <div>
            <h2>{name}</h2>
            <p>Age: {age}</p>
            {onSuperPower && (
                <button onClick={onSuperPower}>
                    Activate Super Power!
                </button>
            )}
        </div>
    );
};

提示和技巧

  1. 從簡單開始:從基本型別開始,逐漸加入更複雜的型別。
  2. 使用編譯器:TypeScript 的編譯器是你的朋友 - 注意它的錯誤。
  3. 不要過度輸入:有時任何都可以(但要謹慎使用!)。
  4. 啟用嚴格模式:將 "strict": true 新增至您的 tsconfig.json 以獲得最大程度的保護。

常見問題及解決方法

// Problem: Object is possibly 'undefined'
const user = users.find(u => u.id === 123);
console.log(user.name); // Error!

// Solution: Optional chaining
console.log(user?.name);

// Problem: Type assertions
const input = document.getElementById('myInput'); // Type: HTMLElement | null
const value = input.value; // Error!

// Solution: Type assertion or type guard
const value = (input as HTMLInputElement).value;
// or
if (input instanceof HTMLInputElement) {
    const value = input.value;
}

總結

TypeScript 乍看之下似乎是額外的工作,但它就像擁有一種超能力,可以幫助您在錯誤發生之前捕獲它們。從小處開始,逐漸添加更多類型,在您意識到之前,您會想知道沒有它您是如何生活的!

記住:

  • 類型是你的朋友
  • 編譯器是你的助手
  • 熟能生巧

以上是TypeScript:JavaScript 的超級英雄斗篷的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn