Property 'instance' does not exist on type 'Http'
When creating a class in typescript, you need to declare all of the class properties and their types.
import axios, {AxiosInstance, AxiosRequestConfig} from "axios";
class Http {
public instance: AxiosInstance;
/* ... */
}
You can get around this requirement when you use a body-less constructor to set the constructor arguments as instance variables. But in this case you are creating a property within the constructor, so you need to declare it at the top level of the class.
Object is possibly 'null'
Additionally, you need to declare types for some of your constructor arguments because they cannot be properly inferred. Basically typescript takes the type of your default value and assumes that the type of the default is the type of the argument. So timeout = 8000 is fine because timeout is assumed to be number (though personally I add the type anyways for consistency).
But interceptors = null is going to cause problems because typescript doesn’t know what the type of interceptors is supposed to be when it’s not null. It actually assigns the type of interceptors as null, so even after checking that it exists you'll still get an error Object is possibly 'null'.
You probably already have a type for this object somewhere in your code base, but based on this code snippet alone it has to have a property hook which can take your instance:
interface Interceptors {
hook( instance: AxiosInstance ): void;
}
In order to use null as the default value, we have to say that this variable can be either, aka Interceptors | null.
For headers and config, these need to be typed to something which axios can accept. AxiosRequestConfig actually says that the headers can be any, but let's limit it to a string-keyed object aka Record<string, any>. For the config we'll just use the AxiosRequestConfig type we imported from axios. We could get fancy and Omit the properties that we are overriding, but it's unnecessary since they are already optional.
A properly typed constructor might look something like
constructor(
baseURL: string,
headers: Record<string, any> = {},
config: AxiosRequestConfig = {},
interceptors: Interceptors | null = null,
timeout: number = 8000
) {
Typescript Playground Link