欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > TypeScript:泛型、模块、文件读写与异步编程

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

2025/2/24 20:58:09 来源:https://blog.csdn.net/time_silence/article/details/145038261  浏览:    关键词: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();

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词