Typescript error occurs when assigning VITE_API_URL in baseURL of axios
P粉014218124
P粉014218124 2024-03-19 16:45:32
0
1
468

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;

P粉014218124
P粉014218124

reply all(1)
P粉176980522

You can enhance ImportMetaEnv Add input to any custom environment variables you are using:

  1. In src/env.d.ts (create if necessary), add the following code:

    /// 
    
    interface ImportMetaEnv {
      readonly VITE_API_URL: string
    }
    
  2. If using VS Code, you may need to restart the TypeScript server (or the IDE itself) to reload types.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!