分类 JavaScript 与 TypeScript 下的文章

 function getDistance(lat1, lon1, lat2, lon2) {
      const R = 6371 // 地球半径,单位为公里
      const dLat = deg2rad(lat2 - lat1)
      const dLon = deg2rad(lon2 - lon1)
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
      return R * c // 距离,单位为公里
    }

    function deg2rad(deg) {
      return deg * (Math.PI / 180)
    }

调用使用

getDistance(30.257665, 119.955635, 30.318454, 120.10968) // 返回数值单位公里

  1. compilerOptions:编译器选项,用于配置编译过程中的行为。

    • "target":指定要编译的 ECMAScript 目标版本(例如:"ES5"、"ES6"等)。
    • "module":指定生成的模块规范(例如:"commonjs"、"es2015"、"amd"、"umd"等)。
    • "outDir":指定编译后的 JavaScript 文件存放目录。
    • "strict":启用所有严格类型检查选项。
    • "esModuleInterop":允许导入默认导出模块以与非默认导出模块进行交互。
    • "allowJs":允许编译 JavaScript 文件。
    • "sourceMap":生成对应的 .map 文件,用于调试 TypeScript。
    • "declaration":生成相应的 .d.ts 声明文件。
    • "noImplicitAny":禁止隐式的 any 类型。
    • "noUnusedLocals":禁止未使用的局部变量。
    • "noUnusedParameters":禁止未使用的函数参数。
    • "strictNullChecks":启用严格的空值检查。
    • "jsx":指定 JSX 代码的生成(例如:"react"、"preserve"、"react-native"等)。
    • "lib":指定要包含的库文件。
    • "baseUrl":基本目录解析的基准目录。
    • "paths":指定模块名称到基于 baseUrl 的路径映射。
    • "rootDir":指定源文件的根目录。
  2. include:指定要包含的文件或目录,可以使用 glob 模式。
  3. exclude:指定要排除的文件或目录,可以使用 glob 模式。
  4. extends:引用另一个 tsconfig.json 文件的路径,允许继承和合并配置。
  5. files:指定要编译的文件列表,而不是使用 includeexclude 来匹配文件。
  6. references:指定项目引用的其他 TypeScript 项目。


import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

export default class ApiClient {
  private axiosInstance: AxiosInstance;

  constructor(config?: AxiosRequestConfig) {
    this.axiosInstance = axios.create(config);
  }

  public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.get(url, config);
    return response.data;
  }

  public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.post(url, data, config);
    return response.data;
  }

  public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.put(url, data, config);
    return response.data;
  }

  public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.axiosInstance.delete(url, config);
    return response.data;
  }
}

使用

import ApiClient from "../utils/apiClient";
 const api = new ApiClient({ baseURL: 'https://api.example.com' });
 export default async function getUser() {
     return await api.get('/users');
}

import nodemailer from "nodemailer";

interface MailOptions {
  to: string;
  subject: string;
  text?: string;
  html?: string;
}

export class EmailUtil {
  private static readonly transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  public static async sendEmail(options: MailOptions): Promise<void> {
    const mailOptions: nodemailer.SendMailOptions = {
      from: process.env.EMAIL_USER,
      to: options.to,
      subject: options.subject,
    };

    if (options.text) {
      mailOptions.text = options.text;
    }

    if (options.html) {
      mailOptions.html = options.html;
    }

    try {
      await this.transporter.sendMail(mailOptions);
      console.log(`Email sent to ${options.to}: ${options.subject}`);
    } catch (error) {
      console.error(`Error sending email to ${options.to}: ${error}`);
    }
  }
}

使用方法


//使用方法
 await EmailUtil.sendEmail({
     to: "recipient@example.com",
     subject: "Test Email",
     text: "This is a test email.",
});

import { CronJob } from 'cron';

class CronUtil {
  // jobMap记录了所有的CronJob实例
  private static jobMap: Map<string, CronJob> = new Map<string, CronJob>();

  /**
   * 添加一个定时任务
   * @param name 任务名称,用于唯一标识任务
   * @param cronTime cron表达式
   * @param onTick 定时任务回调函数
   * @param onComplete 任务完成回调函数
   */
  static addJob(name: string, cronTime: string, onTick: () => void, onComplete?: () => void): void {
    if (this.jobMap.has(name)) {
      throw new Error(`Cron job with name ${name} already exists`);
    }

    const job = new CronJob(cronTime, onTick, onComplete, true);
    this.jobMap.set(name, job);
  }

  /**
   * 启动指定名称的任务
   * @param name 任务名称
   */
  static startJob(name: string): void {
    const job = this.jobMap.get(name);
    if (!job) {
      throw new Error(`No cron job found with name ${name}`);
    }

    if (!job.running) {
      job.start();
    }
  }

  /**
   * 停止指定名称的任务
   * @param name 任务名称
   */
  static stopJob(name: string): void {
    const job = this.jobMap.get(name);
    if (!job) {
      throw new Error(`No cron job found with name ${name}`);
    }

    if (job.running) {
      job.stop();
    }
  }

  /**
   * 停止所有任务
   */
  static stopAllJobs(): void {
    for (const [_, job] of this.jobMap) {
      job.stop();
    }
  }
}

export default CronUtil;

使用方式

//任务调度器
CronUtil.addJob('myJob', '*/5 * * * * *', () => {
   console.log('Job executed!');
});

CronUtil.startJob('myJob');