0

I am doing an online learning class to learn Angular. (LinkedIn Learning - Building Angular and ASP.NET Core Applications) in this class an interface to store a Book object is created in a subfolder interfaces under the scr/app directory. Then it appears immediately for use in components and services.

I, coming from a C++/C# background, am trying to understand how the interface is globally available as an object to be used in components or services. The project compiles and works, my question is how? The things that I would think you need to make the interface available don't exist in this project

  • There is no export statement to the interface
  • The interface is not imported into the file being used
  • The interface is not declared in the app.module.ts file

book.ts

interface Book {
  id: number;
  title: string;
  description: string;
  author: string;
  rate?: number;
  dateStart?: Date;
  dateRead?: Date;
}

Example of Component

export class ShowBookComponent implements OnInit {
  book: Book;

Example of Service

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BookService {
  _baseURL: string = "api/Books";

  constructor(private http: HttpClient) { }

  getAllBooks() {
    return this.http.get<Book[]>(this._baseURL+"/GetBooks");
  }
Mike
  • 5,918
  • 9
  • 57
  • 94
  • https://stackoverflow.com/questions/48407143/why-dont-i-need-to-export-import-typescript-interfaces#comment83803735_48407143. If you add `export` to the interface, you'll see you _do_ then need to `import` it elsewhere. – jonrsharpe Jun 08 '22 at 15:42
  • Right, so my question is the opposite, why does not adding export make it globally available? – Mike Jun 08 '22 at 15:46
  • 1
    ...because _"If you have no import or export in your file, it's not a module..."_ – jonrsharpe Jun 08 '22 at 15:47
  • Can you compile it ? No TS Errors ? – Ricardo Machado Jun 08 '22 at 15:52
  • Yes it compiles and works my question is how is this interface globally available – Mike Jun 08 '22 at 15:53
  • I think so the key line and the point you @jonrsharpe was trying to make that I now understand "So, it seems like if you don't export anything in the file, it's treated as a global. I suspect that if export anything, the file becomes a module." – Mike Jun 08 '22 at 15:58
  • 1
    I'ts new for me :) So i'm searching with you and i've seen that: https://stackoverflow.com/questions/69446931/typescript-stop-file-from-becoming-a-module A better explanation of what @jonrsharpe was saying. – Ricardo Machado Jun 08 '22 at 16:08

0 Answers0