typescriptaxiospromisevuejs3

How to migrate code with axios and promises to TypeScript?


I have a project written in Vue 2 (Options API)/JavaScript. The goal is to migrate to Vue 3 (Composition API)/TypeScript.

There is a code that works with API and I don't understand some TypeScript messages. The code looks as following:

import axiosInstance from './axiosInstance'

export default new (class bmRequest {
    username = 'user'
    password = '123456'

    token: string = null
    tokenInProcess: boolean = false

    auth() {
        if (this.tokenInProcess) {
            return this.tokenInProcess
        }
        return new Promise((resolve, reject) => {
            if (this.token) {
                resolve(true)
                return
            }
            this.tokenInProcess = axiosInstance
                .post('/auth', {
                    login: this.username,
                    password: this.password,
                })
                .then((response) => {
                    if (response.status === 200) {
                        this.token = response.data.SESSION_TOKEN
                        this.tokenInProcess = undefined
                        return true
                    } else {
                        this.tokenInProcess = false
                        return false
                    }
                })
            resolve(this.tokenInProcess)
        })
    }

    public get(url: string, params: { SESSION_TOKEN: string }) {
        return new Promise((resolve, reject) => {
            this.auth().then((status) => {
                if (status) {
                    params = { SESSION_TOKEN: this.token }
                    axiosInstance
                        .get(url, {
                            params,
                            headers: {
                                'Content-Type': 'application/json',
                                'Access-Control-Allow-Origin': '*',
                            },
                        })
                        .then((response) => {
                            resolve(response.data)
                        })
                        .catch((err) => {
                            reject(err)
                        })
                        .then(() => {})
                } else {
                    resolve(null)
                }
            })
        })
    }

Please, take a look at the screen shots with TypeScript messages:

enter image description here

enter image description here

How to get rid of them?

And the second question - is this approach (promises and axios) good enough or we could do it in another way such as using axios only, async/await etc.?


Solution

  • tokenInProcess: boolean = false
    

    You've defined tokenInProcess as a boolean type but then you assign a Promise. Change the type accordingly

    tokenInProcess?: Promise<boolean> = null
    

    This should also fix your other error as now auth() only returns a Promise.