TypeScript:泛型、模块、文件读写与异步编程

TypeScript是一种强类型的JavaScript超集。

1. 泛型

泛型(Generics)是一种让类型参数化的工具,可以编写更加灵活且类型安全的代码。

泛型函数
function identity<T>(value: T): T {
    return value;
}
const numberValue = identity<number>(42); // number类型
const stringValue = identity<string>("Hello!"); // string类型
泛型接口
interface Pair<T, U> {
    first: T;
    second: U;
}
const pair: Pair<string, number> = { first: "age", second: 30 };
泛型类
class Stack<T> {
    private items: T[] = [];
    push(item: T) {
        this.items.push(item);
    }
    pop(): T | undefined {
        return this.items.pop();
    }
}
const stack = new Stack<number>();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // 输出: 20

2. 模块化

TypeScript支持模块化,可以将代码拆分为多个文件进行管理,并通过importexport进行交互。

定义与导出模块

创建一个mathUtils.ts文件:

export function add(a: number, b: number): number {
    return a + b;
}
export const PI = 3.14159;
导入模块

在另一个文件中:

import { add, PI } from './mathUtils';
console.log(add(10, 20)); // 输出: 30
console.log(PI); // 输出: 3.14159
默认导出
export default function greet(name: string): string {
    return `Hello, ${name}!`;
}
import greet from './mathUtils';
console.log(greet("Alice")); // 输出: Hello, Alice!

3. 文件读写

在TypeScript中,可以使用fs模块来读写文件。

读写.txt文件
import * as fs from 'fs';

// 写入数据到.txt文件
fs.writeFileSync('example.txt', 'This is a TypeScript example.');

// 从.txt文件读取数据
const content = fs.readFileSync('example.txt', 'utf-8');
console.log(content); // 输出: This is a TypeScript example.
读写.json文件
// 写入JSON数据
const data = { name: "Alice", age: 30 };
fs.writeFileSync('data.json', JSON.stringify(data, null, 2));

// 读取JSON数据
const jsonData = JSON.parse(fs.readFileSync('data.json', 'utf-8'));
console.log(jsonData); // 输出: { name: "Alice", age: 30 }

4. 异步编程

TypeScript支持多种异步编程方式,包括回调函数、Promise和async/await。

回调函数
import * as fs from 'fs';
fs.readFile('example.txt', 'utf-8', (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(data); // 异步读取文件内容
});
Promise
import * as fs from 'fs/promises';
fs.readFile('example.txt', 'utf-8')
    .then(data => console.log(data))
    .catch(err => console.error(err));
async/await
import * as fs from 'fs/promises';
async function readFileAsync() {
    try {
        const data = await fs.readFile('example.txt', 'utf-8');
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}
readFileAsync();

凡是过去,皆为序章;凡是未来,皆有可期。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值