Home > front end >  TypeScript - Get type interface in package node modules
TypeScript - Get type interface in package node modules

Time:10-07

Problem

For example, I would use a new AxiosInstance like:

import axios from "axios";

const api = axios.create({
    baseURL: process.env.REACT_APP_BASE_URL || "http://localhost:8888"
})

class Service {
    mainService = api;
}

Then I would like to add changeService method to Service class above:

class Service {
    mainService = api;
    changeService(api) {
        this._service = api;
    }
}

This would trigger type checking of TypeScript because of changeService(api).

Question

Because of axios.create() will return an AxiosInstance. Along with being new to TypeScript, I am thinking about trying to get the type of AxiosInstance interface of axios package.

How could I achieve this? Or are there better ways to deal with this situation?

CodePudding user response:

You just add it to what you are importing from the axios module.

import axios, { AxiosInstance } from "axios";

Then use it like so:

class Service {
    mainService = api;
    changeService(api: AxiosInstance) {
        this.mainService = api;
    }
}

See Playground

  • Related