What is the reason for not receiving a transpilation error when referencing a non-exported class?

As a relatively new learner of Typescript and Javascript (with a background in Java), I have been navigating the transition from a single large Typescript file containing multiple classes to utilizing multiple classes. While I have made progress with the

import {ClassName} from './{Classname}'
syntax, along with ensuring that Classname is preceded by export class ClassName, I have encountered a recent setback. Initially, the transition seemed seamless, especially with my Java background where compiler errors were caught easily by Netbeans and tsc. However, the smooth sailing came to a halt when I encountered a
ReferenceError: ClassToBeImported is not defined
during runtime. It became apparent that the issue stemmed from a missing import of ClassToBeImported, bringing into question the reliability of runtime error checks compared to IDE/transpiler errors.

While attempting to create a simplified example, it dawned on me that the problem may lie in the exporting of the referenced file. By adding or removing the export keyword from export class NeedsToBeImported, the error would appear or disappear accordingly.

The scenario below illustrates the error that arises:

// in file MainClass.ts
export class MainClass{
    constructor(){
        let x = ClassToBeImported.SOME_FIELD;
    }
}

// in file ClassToBeImported.ts, same folder
export class ClassToBeImported{
    static SOME_FIELD : string = "data";
}

On the other hand, the following setup does not throw an error until runtime:

// in file MainClass.ts
export class MainClass{
    constructor(){
        let x = ClassToBeImported.SOME_FIELD;
    }
}

// in file ClassToBeImported.ts, same folder
class ClassToBeImported{
    static SOME_FIELD : string = "data";
}

With the primary question surrounding the puzzling nature of this issue - specifically, why referencing a non-exported class fails to generate a transpilation error - the secondary question pertains to potential measures for enhancing code safety. Is there an option in tsconfig.json (currently targeting es2015) that can be activated to enforce stricter checks, thereby reducing the likelihood of such runtime errors?

Answer №1

When it comes to JavaScript and TypeScript, there are two main types of source files to consider: scripts and modules.

According to the handbook:

In TypeScript, similar to ECMAScript 2015, any file that includes a top-level import or export is classified as a module. On the other hand, a file lacking such declarations is treated as a script, making its contents accessible in the global scope, including to modules.

For instance, if you were to embed the file ClassToBeImported.js using a <script> tag in a webpage, the ClassToBeImported class would then be accessible as a global variable.

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

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Using Angular to handle routes with a specific domain prefix

Let's say I own the domain https://example.com and I'd like to create a subdomain specifically for my blog, like this: https://blog.example.com. How would you handle the routing for this scenario using Angular? ...

Customizing the border of a FloatingActionButton in Material UI

How can I add a border to a FloatingActionButton? Which props should I use to achieve this? The iconStyle property does not seem to work. Here is the link to my code: https://codepen.io/palaniichukdmytro/pen/NgQmve Additionally, I would like to know how t ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...

Can we determine the data type of a value within a class instance by utilizing a function to retrieve it?

Is it feasible to create a function that maintains typing and functions in the same way as this: class Example { someNumber:number = 1; someString:string = "test"; } const example = new Example(); const value = example.someNumber; // typ ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-crops-list', templateUrl: './crops-list.component.html' ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

What could be the reason behind encountering the UnhandledPromiseRejectionWarning error while executing npm build in my serverless application?

I am encountering an issue while attempting to execute npm build on my serverless aws-nodejs-typescript project. I am unsure of how to resolve it. Can someone provide guidance on how to troubleshoot this problem? npm build (node:44390) UnhandledPromiseRej ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Encountering issues with HTML loading interpolation before constructor in TypeScript

I am currently working on a project using Angular 6 and encountering some challenges. Here is the issue at hand: I am facing an error in the HTML Console, which occurs after reloading the page. The error message indicates that the variable "atual" is unde ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

Navigating to a different page in Ionic 2 upon app initialization

Is there a way to automatically redirect the page to the home page instead of displaying the login page if there is already a token stored in localStorage? I currently have the following code in the constructor() of app.component.ts, but it still display ...

Remove Image Upload feature in antDesign and remove item from interface

I am currently working on a project that involves multiple interfaces. One of these interfaces is specifically designed for uploading images. However, I encountered a problem with the deletion icon functionality. Whenever the icon is clicked, a modal is su ...

What could be causing the error that pops up every time I attempt to execute a git push

When I executed the following command in git git push origin <the-name-of-my-branch> I encountered the following warning message Warning: The no-use-before-declare rule is deprecated since TypeScript 2.9. Please utilize the built-in compiler check ...

The defaultValue of the Observable TextArea is blank space following the transmission of a sendMessage using SignalR in a Typescript

i am currently in the process of modifying a basic SignalR Chat feature. Here is the situation: when a user sends a message, the message gets sent successfully. However, the textarea from which it was sent remains filled with empty space (aside from the p ...

Clicking on the Angular custom accordion component does not trigger the expansion feature

I have developed a customized accordion component using Angular 9, but I am encountering an issue. Whenever I click on the accordion, only the first button's window expands while the others remain unaffected. To demonstrate the problem more effective ...