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支持模块化,可以将代码拆分为多个文件进行管理,并通过import
和export
进行交互。
定义与导出模块
创建一个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();
凡是过去,皆为序章;凡是未来,皆有可期。