Using interfaces from a different file becomes challenging as they cannot access any external dependencies when imported

Encountering an issue with interface importing. When the interface contains non-import dependencies and is located in separate files like:

/src/app/something/something.interface.ts

interface ISomething {
    a: String[];
}

I am able to utilize it in another file within the same directory without importing it, for example:

/src/app/someting/something.tsx

class Something extends React.Component<ISomething, any> {

}

However, when the interface includes imports like this:

import Page from '../components/page';

interface ISomething {
    a: String[];
    b: Page;
}

An error is encountered during the compilation process:

[2] ERROR in src/app/something/something.tsx(9,40): error TS2304: Cannot find name 'ISomething'.

Attempting to use export interface ISomething ... and import them in something.tsx results in an error

[2] ERROR in src/app/application/education/react/renderer/renderer.tsx(8,9): error TS2305: Module '"/Users/xxx/Projects/react/src/app/something/something.interface"' has no exported member 'ISomething'.

If I place my ISomething interface in the something.tsx file, it works fine, but I prefer to keep it organized in a separate file.

Any insights on why this might be occurring?

EDIT: tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../dist/out-tsc/app",
    "module": "es2015",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ],
    "angularCompilerOptions": {
        "preserveWhitespaces": true
    }
}

Answer №1

The reason for this behavior in Typescript is quite peculiar and stems from its historical origins. When a file contains no import or export statements and is included in the tsconfig.json file (which by default includes all files in the directory), Typescript interprets it as a script rather than a module, thereby making its identifiers accessible in the global scope.

To change this default behavior, you can modify the module setting in the compilerOptions section of your tsconfig.json file. The appropriate value to use depends on the context in which the code will be used; selecting es6, for instance, should achieve the desired outcome.

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

Encountered an issue with importing a JavaScript library in TypeScript

I am trying to import a JavaScript library called Akarata. I have followed the suggestions from the internet, such as: import * as akarata from 'akarata/dist'; or import * as akarata from 'akarata'; However, I am still encountering ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

Struggling to configure typescript and babel to work together smoothly within webpack

Currently, I am in the process of converting a project to TypeScript, and it is required to utilize decorators on both classes and function parameters: function(@inject(TYPES.thing) thingy){...} I believe I am very close to completing this task, just mis ...

Encountered an issue with retrieving schema during self-referencing validation with openapi generator

I created an openapi specification and now I am looking to generate a client for it. openapi.yaml After some research, I decided to use the openapi generator to create a typescript-axios client. This is the command I used: openapi-generator-cli generate ...

Trigger a type error in TypeScript when the property of an anonymous object does not conform to the specified type

Within my code, I have an unidentified object containing a property with TypeScript type. Here is an example: type Bar = { exists: true; baz: string; }; performAction({ bar: { exists: true, baz: 'qux', } as Bar, }); I am seeking ...

Comparing ESLint and TSLint: Which One Is Right for You

After looking through numerous sources, I came up empty-handed regarding this particular question. Could anyone provide insight on the drawbacks of using Eslint compared to TsLint? What are the reasons for transitioning to ESLint? ...

What is the best way to implement a comprehensive switch case in Typescript using string enums that are referencing other string enums?

I am faced with a challenge where I have a subset of values from one enum that I need to switch case across in TypeScript. Here's an example to illustrate my dilemma: const enum Fruit { APPLE = 'Apple', BANANA = 'Banana', ...

Activate the event when the radio button is changed

Is there a way to change the selected radio button in a radio group that is generated using a for loop? I am attempting to utilize the changeRadio function to select and trigger the change of the radio button based on a specific value. <mat-radio-group ...

Organizing TypeScript files and code within an ASP.NET project

Currently, I am working on an ASP.NET project using .NET 4.6 and Visual Studio 2015. The business logic is primarily written in C#, but there is also a significant amount of client-side logic involved. To help organize my client-side code in a way similar ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Retrieving an element by its id in Angular 2

Hi there, I'm having some trouble with a code snippet: document.getElementById('loginInput').value = '123'; When trying to compile the code, I keep getting this error message: "Property value does not exist on type HTMLElement ...

What is the best way to prevent styles.css in Angular from impacting all elements with the same selector?

Although I can align the content of my grid tiles, I only intended for it to affect the table that was inside a grid. This is what I have: .mat-grid-tile .mat-figure { justify-content: flex-start !important ; align-items: flex-start !important; } ...

Requesting Next Page via Angular GET Method for Paginated API

Having trouble loading data from a paginated REST API using the code below. Any suggestions for a better approach are welcome! component.ts import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http&a ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

In Angular, a variable that is exported from a module may not be accessible within a class function

Within my Angular project, I have a service file where I export a variable to be used in another file (component.ts). Interestingly, when I access the value of this variable outside of the class, everything works as expected. However, if I try to access i ...

The geolocation feature is operational in the browser test, but it is not functioning properly on the

I am currently creating an application that requires accessing the user's location at a specific point in time. To achieve this, I have utilized the ionic native geolocation feature which communicates with the Google API for reverse geocoding. Everyt ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

I am unable to locate the appropriate TypeScript type for the `displayName` attribute when it is used as a prop for the `type` component

Having trouble finding the correct type as mentioned in the title. After inspecting with DevTools, I have confirmed that every component I am programmatically looking at has Component.type.displayName. For anything that is not an ElementType, the type is a ...