常用Typescript代码留档

1. 声明变量

let message: string = "Hello, TypeScript!";

2. 使用接口定义对象结构

interface Person {
    name: string;
    age: number;
}

const person: Person = { name: "Alice", age: 30 };

3. 类和继承

class Animal {
    move(distanceInMeters: number = 0) {
        console.log(`Animal moved ${distanceInMeters}m.`);
    }
}

class Dog extends Animal {
    bark() {
        console.log("Woof! Woof!");
    }
}

const dog = new Dog();
dog.bark();
dog.move(10);

4. 泛型函数

function identity<T>(arg: T): T {
    return arg;
}

let output = identity<string>("hello");

5. 类型推断

let x = 3; // 类型推断为 number

6. 可选属性和只读属性

interface SquareConfig {
    color?: string;
    width: number;
    readonly height: number;
}

let config: SquareConfig = { width: 100, height: 200 };
config.color = "red";

7. 函数类型

let myAdd: (x: number, y: number) => number = function(x, y) { return x + y; };

8. 索引类型

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Alice"];
let firstItem: string = myArray[0];

9. 类型别名

type Name = string;
let myName: Name = "Alice";

10. 枚举

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

11. 使用命名空间组织代码

namespace Geometry {
    export interface Vector2D {
        x: number;
        y: number;
    }

    export function calculateLength(v: Vector2D) {
        return Math.sqrt(v.x ** 2 + v.y ** 2);
    }
}

let vector: Geometry.Vector2D = { x: 3, y: 4 };
let length = Geometry.calculateLength(vector);

12. 类型断言

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

13. 使用模块化

// math.ts
export function sum(x: number, y: number): number {
    return x + y;
}

// app.ts
import { sum } from "./math";
let result = sum(3, 5);

14. 处理空值

function getLength(s: string | null): number {
    return s ? s.length : 0;
}

15. 使用装饰器

function log(target: any, key: string) {
    console.log(`${key} was called`);
}

class MyClass {
    @log
    myMethod() {
        // Method logic
    }
}

16. 使用 async/await 处理异步代码

function delay(ms: number) {
    return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

async function hello() {
    await delay(1000);
    console.log("Hello, TypeScript!");
}

hello();

17. 使用类型守卫处理联合类型

function isNumber(x: any): x is number {
    return typeof x === "number";
}

function example(foo: number | string) {
    if (isNumber(foo)) {
        console.log("It's a number: " + foo);
    } else {
        console.log("It's a string: " + foo);
    }
}

18. 实现接口

interface Clock {
    currentTime: Date;
    setTime(d: Date): void;
}

class MyClock implements Clock {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
}

19. 使用类型推断简化代码

let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(n => n * n);

20. 使用泛型约束

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}

loggingIdentity({ length: 10, value: 3 });
THE END