I have a very basic axios setup on a Vue 3 application built on Vite and Typescript. However, I get a typescript error for "baseURL" which reads:
Input 'string|'boolean|undefined' is not assignable to type 'string|undefined'. Type 'false' is not assignable to type 'string |' undefined'.ts(2322)
As explicitly implied, VITE_API_URL
is of type string | boolean | undefined
, but baseURL
does not like to accept boolean values. Now, obviously I'm not trying to assign a boolean value to this property, but its type suggests it might, and that's enough to mess with it.
Now Vite defines an interface for VITE_API_URL
, as follows:
interface ImportMetaEnv { [key: string]: string | boolean | undefined BASE_URL: string MODE: string DEV: boolean PROD: boolean SSR: boolean }
If I were the one creating this interface, I would just remove the boolean since I would never set a boolean for this value, but I'm not satisfied that changing Vite's built-in interface is the correct course of action here.
I'm still expanding my Typescript knowledge, so I'm hoping this is something simple I'm missing, but I can't seem to find any solution to get these two to play nicely. Considering how popular Vite and Axios are, I'm hoping someone else has encountered this problem and found a simple solution. Any help would be greatly appreciated!
httpClient.ts
is as follows:
import axios from 'axios'; const httpClient = axios.create({ baseURL: import.meta.env.VITE_API_URL, headers: { 'Content-Type': 'application/json', }, }); export default httpClient;
You can enhance
ImportMetaEnv
Add input to any custom environment variables you are using:In
src/env.d.ts
(create if necessary), add the following code:If using VS Code, you may need to restart the TypeScript server (or the IDE itself) to reload types.