Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question:

module someModule {
declare var servicePort: string;

export class someClass{
constructor(){
  servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined'
}

I also attempted this approach within a function inside "someClass":

someFunction = () => {
    if (servicePort && servicePort != '') { //ERROR - also servicePort is not defined
            //do something with servicePort 
        }
}

When I define var servicePort in my js /html files, it works. However, since not all pages include the servicePort variable, I want to safely retrieve its value without causing exceptions. What mistake am I making?

Answer №1

It's not ideal to have a variable that is sometimes defined and sometimes not in your code, but if you absolutely must do this, make sure to protect access to that variable using typeof:

if (typeof servicePort !== "undefined") {
   // It's safe to use servicePort here
}

Keep in mind that distinguishing between a missing variable and one with the value undefined can be challenging, but that's just how it is.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Tips for positioning text on the left and right sides of a div in HTML styling

I am struggling with positioning two pieces of text within a div. Despite having some styling already in place, the text is currently displaying one after the other on the left-hand side. I want to position one piece of text to the left and another to the ...

Stop JSON.parse from shuffling the order of an object

When working on my web application, I retrieve a JSON string from the server and store it in a variable called greetings: var greetings = '{"2":"hoi","3":"hi","1":"salam"}' I have obser ...

Can you tell me the alternatives for getServerSideProps and getStaticProps in Next.js version 14?

I'm trying to wrap my head around the rendering behavior of SSR/SSG/ISR in Next.js version 14 with the updated app router. Previously, Next.js provided predefined functions like getServerSideProps for server-side fetching and processing (SSR), or getS ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

Using the typescript infer feature does not function properly when dealing with arrays

My TypeScript code is causing some unexpected results: const myObject = { foo: ['a', 'b', 'c'] } type MyType = typeof myObject.foo extends [...infer Content] ? string : boolean The type MyType is coming out as 'string ...

Personalize the "set up notification" PWA on React

Is it possible to customize this default design, including the picture, title, description, and background? I made changes in manifest.json, but nothing seems to have happened. Here is a picture of the random install prompt that I would like to customize ...

I am in search of a JavaScript or jQuery plugin for an HTML slider with a unique range functionality

I've been searching online but couldn't find a slider like the one shown in the attachment. Can anyone help? Is there a way to create this specific slider or is there an existing plugin or library for it? Please refer to the image below :https:/ ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Initiate the Bull Queue Process upon launching the Application

As I develop my API, I am setting up a queue and adding jobs to it. Additionally, I have configured the API to start processing these jobs as soon as they are added. const newQueue = createQueue(queueName, opts); newQueue.add('JokesJob', data, o ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

What is the best way to construct an AJAX call that includes two sets of POST data?

I'm currently working on a project that involves sending WebGL frames/screenshots to a server for saving to the hard drive and later merging them into a video file. I came across this helpful resource: Exporting video from WebGL Without delving too m ...

Combine Typescript files from a dependent module to aid in debugging within a Next.js application

Trying to debug a project written in Typescript using Next.js, but facing issues with bundling TS files from a local dependent common library. Only JS files are included, which is not sufficient for debugging. The goal is to bundle all TS files from the w ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

Rearrange the entire div container by simply dragging and dropping it. (Shift the Pop-up Modal dialog box)

How can I make a Modal pop-up draggable and change the color of the "Ok" and "Cancel" buttons on hover using a single CSS class? .hidModal{ position: fixed; font-family: Arial, Helvetica, sans-serif; top: 0; right: 0; bottom: 0; ...

triggering a method in an Angular controller using a Google API embedded in the view

Using the Google Places Details API, I have included a Google API with a callback function called initMap in the src attribute. Here is the code snippet: <div class="tab-pane active" id="timeline"> <p class="lead">Location</p> <hr& ...

Convert a TypeScript array of strings to a boolean array: a step-by-step guide

Upon receiving a list of objects from the front end as: item=["false","true"] I proceed to check a column within my records to identify values containing "true" or "false" using the following code: this.records.filter(x=> items.includes(x.column)) Unf ...

Using Thymeleaf within Javascript code to generate a URL?

Here is my question: The project's base URL is : The test page URL is :, and on this page, I have included a JavaScript file called datatable.packer.js using the following code: <script type="text/javascript" th:src="@{/resources/js/datatable ...

Alter the font color of text using JavaScript in an HTML document

I am struggling to change the title color in my HTML code below, but the text color does not seem to be changing. How can I make this adjustment? /** * Generate a HTML table with the provided data */ Highcharts.Chart.prototype.generateTable ...

Tips for obtaining a JSON response from a RESTful API in AngularJS by utilizing the $resource service

I have been working on my AngularJS code, and although I am receiving a response in the console, I am having trouble storing it in an array or JSON format. angular.module('user', ['ngResource']). config(function($httpProvider){ $h ...