Issue
I have a very basic axios setup on a Vue 3 application built on Vite & Typescript. However, I’m receiving a typescript error for "baseURL" that reads:
Type ‘string | boolean | undefined’ is not assignable to type ‘string | undefined’.
Type ‘false’ is not assignable to type ‘string | undefined’.ts(2322)
As clearly implied VITE_API_URL
is of type string | boolean | undefined
, but baseURL
doesn’t like accepting booleans. Now, obviously I’m not attempting to assign a boolean to this property, but its typing indicates it could be, which is enough to upset it.
Now Vite has an interface defined 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 who created this interface, I’d just remove the boolean, as I’ll never be setting a boolean for this value, but I’m not satisfied that changing Vite’s built-in interface is the right course of action here.
I’m still expanding my Typescript knowledge, so I’m hoping this is something simple that I’m missing, but I cannot seem to find any solutions to getting these two to play nice. Considering how prevalent both Vite and Axios are, I’m hoping someone else has run into this and found a simple solution. Any help would be appreciated!
httpClient.ts
below:
import axios from 'axios';
const httpClient = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
'Content-Type': 'application/json',
},
});
export default httpClient;
Solution
You can augment ImportMetaEnv
to add the type for any custom environment variables you’re using:
-
In
src/env.d.ts
(create if needed), add the following code:/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_API_URL: string }
-
If using VS Code, you might need to restart the TypeScript server (or the IDE itself) for the types to be reloaded.
Answered By – tony19
Answer Checked By – Mildred Charles (BugsFixing Admin)