Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil.

Within the confines of file application.ts, a code structure unfolds:


class APPLICATION {
    constructor(){
        console.log("constructor APPLICATION")
        this.database = new REPOSITORY
    }
    
    database: REPOSITORY
}

new APPLICATION

import { REPOSITORY } from "./repository"

Turning towards file repository.ts, another segment of code materializes:


export class REPOSITORY {
    constructor() {
        console.log("constructor de REPOSITORY")
    }
}

Nevertheless, an error disrupts the harmony:

this.database = new repository_1.REPOSITORY;
                                    ^
<<TypeError: Cannot read property 'REPOSITORY' of undefined
    at new APPLICATION (Z:\Documents\Phi\Developpement\TypeScript\test\application.js:6:41)>>

Lost in a maze of uncertainties, any flicker of an idea would be greatly appreciated.

Answer №1

Indeed, you are absolutely correct! I also initially believed the compiler operated in two passes and that the sequence of statements was not crucial. In my opinion, it would be more convenient if the import/export mechanism happened automatically, allowing it to be hidden at the conclusion of the code. What a missed opportunity!

Many thanks

Answer №2

The REPOSITORY import statement must be placed before it is used in the constructor of the APPLICATION class. This is because the variable assignment from the import statement is not hoisted, meaning that REPOSITORY needs to be defined prior to its use:

import { REPOSITORY } from "./repository"

class APPLICATION {
    constructor(){
        console.log("constructor APPLICATION")
        this.database = new REPOSITORY();
    }
    database: REPOSITORY
}

Answer №3

It's my understanding that imports are not hoisted in JavaScript. If you're experiencing issues, consider reordering your code and moving the line

import { REPOSITORY } from "./repository"
to an earlier position.

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

What is the method for modifying the chosen color using a select option tag instead of a list?

element, I have a Vue component that features images which change color upon clicking a list item associated with that color. <div class="product__machine-info__colors"> <ul> <li v-for="(color, index) in machine.content[0] ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

Defer the rendering of Vue.js pages until the data request is completed

I am currently working on a page that retrieves data from the server using axios. My goal is to wait for the axios request to complete before rendering the page content. The reason behind this approach is that I already have a prerendered version of the ...

Specializing in narrowing types with two generic parameters

In my current project, I am working on a function that takes two generic parameters: "index" which is a string and "language" which can also be any string. The goal of the function is to validate if the given language is supported and then return a formatt ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

Avoid opening the page when attempting to log in with jquery, ajax, and php

I am facing an issue with my code. I have a file named "index.html" which contains a login form. Another file called "dash.js" retrieves the username and password from the login form and redirects to "connectdb.php" to check the login credentials with the ...

Utilizing props for toggling the navigation list, incorporating nested arrays or objects

My issue involves two components that are loading data. I want the links to be output like this: group1 linka linkb However, they are currently displaying like this: group1 linka group1 linkb I believe the problem lies in how I am handling the ...

The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet: <div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria- ...

Convert a relative path to an absolute path using the file:// protocol

When I scrape a website with similar html content, I come across the following code: <a href="/pages/1></a> In addition to this, I have access to the window.location object which contains: origin:"http://www.example.org" This allows me to ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...

Ensure that the user remains within the current div when they click the submit button, even if the textbox is

For the past 48 hours, I've been grappling with an issue on my HTML page that features four divs. Each div contains three input fields and a button. The problem arises when a user leaves a text box empty upon submitting - instead of staying in the sam ...

Can you explain the distinction between JSON syntax and object assignment in programming?

While exploring the Twitter Client example on Knockoutjs, one may notice that some properties are included in the JSON object while others are assigned outside of it. What distinguishes these two approaches? And why can't methods such as findSavedList ...

Is it possible in Javascript to trace the origins of a particular element's property inheritance for debugging purposes?

I'm currently dealing with an issue where the computed style font-size of a particular element is "16px". I've been attempting to pinpoint where in the CSS or JavaScript this font size setting is coming from, specifically within one of its parent ...

Error retrieving user by provider account ID using Google and Firebase adapter with Next Auth

Encountering an issue while trying to integrate Google Provider with Firebase Adapter in Next Auth. Upon selecting an account, the following error is displayed: Running Firebase 9 TypeError: client.collection is not a function at getUserByProvider ...

Exploring the View-Model declaration in Knockout.js: Unveiling two distinct approaches

For my latest project, I am utilizing Knockout.js to create a dynamic client application with numerous knockout.js ViewModels. During development, I came across two distinct methods of creating these ViewModels. First method: function AppViewModel() { thi ...

"Trouble accessing the URL" error encountered when trying to load templateUrl for dynamic components in Angular 2

Attempted to modify a solution found here. The modification works well, but when changing the template to templateUrl in the component that needs to be loaded dynamically, an error occurs: "No ResourceLoader implementation has been provided. Can't rea ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...