Typescript - Declare optional global variable

怎甘沉沦 提交于 2021-01-27 08:03:16

问题


I am creating a service to check if a user is logged in. This will just be a global variable 'userIsLoggedIn' which is passed from the backend. This service will be used across several applications and sometimes the userIsLoggedIn global variable will not exist.

What I have is...

import { Injectable } from '@angular/core';

declare const userIsLoggedIn: boolean;

@Injectable()
export class UserLoggedInService{
    isUserLoggedIn(): boolean {
        return userIsLoggedIn || false;
    }
}

If the userIsLoggedIn global variable does not exist then I get an error and if I leave out the declaration line then I get an error.

I had hoped to be able to do something like

declare const userIsLoggedIn?: boolean;

But this does not seem to work. Could anybody help me out please?

来源:https://stackoverflow.com/questions/46929754/typescript-declare-optional-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!