I am trying to implement a small typescript Vue3 app as a training exercise. I am making pretty good progress, but have run into a hurdle. Some advice from those more knowledgeable than me would be appreciated.
I have been setting up authorisations using firebase and am implementing route guards. These work, except in the case where the user types the new route directly in the address bar. In this case it seems to recreate teh app before it has the information regarding the looged in user. It therefore thinks the user is null, and renders the Login Page. So I am advised to implement the following.
main.ts
import App from './App.vue'
import { createApp, App as Application } from 'vue'
import router from './router'
import { projectAuth } from './firebase/config'
import { onAuthStateChanged } from 'firebase/auth'
let app: Application
onAuthStateChanged(projectAuth, () => {
if (!app) {
app = createApp(App) // type error on 'app'
.use(router)
.mount('#app')
}
})
It works as a pure Javascript implementation, but throws a type error in typescript.
How can I define the type of app in the above code?
I have tried several variations, all ineffective, including:
let app: typeof App
let app: App<Element>
let app: typeof Application
I guess it is something simple, but as a typescript newbie it eludes me.
CodePudding user response:
Import App
type from vue
, rename it to something like Application
to avoid collapsing with your App
component, and then annotate your app
with type Application
:
import { createApp, App as Application } from 'vue'
let app: Application;
onAuthStateChanged(projectAuth, () => {
if (!app) {
app = createApp(App).use(router)
app.mount('#app') // do not chain mount after createApp
}
}