ค้นหาเว็บไซต์

เพิ่มการส่งออกเริ่มต้นใน TypeScript?


แพ็กเกจบางตัวส่งออกเพียงวัตถุเดียวเท่านั้น หากฉันต้องการเขียนทับ/ขยายวัตถุนั้น: ฉันจะทำอย่างไร?

หลังจากค้นหาคำตอบมากมาย นี่คือจุดที่ฉันอยู่:

import axios from "axios";

declare module "axios" {
  const axios: {
    not: () => void;
  };

  export = axios; // <- Exports and export assignments are not permitted in module augmentations.
}

axios.not();

คำถามนี้ไม่เกี่ยวกับว่าการเขียนทับ axios ที่นี่เป็นเรื่องปฏิบัติได้หรือไม่

คำตอบ #1

TypeScript มีความสามารถในการรวมการประกาศ น่าเสียดายที่ในกรณีของคุณ คุณจะไม่สามารถใช้ประโยชน์จากมันได้เนื่องจากข้อจำกัดของมัน:

การรวมที่ไม่อนุญาต ไม่ใช่ทุกการรวมที่จะได้รับอนุญาตใน TypeScript ปัจจุบัน คลาสไม่สามารถรวมกับคลาสอื่นหรือกับตัวแปร สำหรับข้อมูลเกี่ยวกับการเลียนแบบการรวมคลาส โปรดดูที่ส่วน Mixins ใน TypeScript

ตามที่เอกสารกล่าว อย่างไรก็ตามคุณสามารถใช้มิกซินเพื่อสร้างคลาสของคุณเองที่ขยาย Axios:

import { Axios } from "axios";

type AxiosConstructor = new (...args: any[]) => Axios;

function augmentAxios<T extends AxiosConstructor>(axios: T) {
    return class AugmentedAxios extends axios {
        newAbility() {}
    };
}

const AugmentedAxios = augmentAxios(Axios);

const augmentedAxios = new AugmentedAxios({});

augmentedAxios.post('http://test'); // Base ability
augmentedAxios.newAbility(); // New ability