Exporting Typescript to Javascript files

I have created a sample TypeScript object with the following code:

declare const S3 = "https://s3.amazonaws.com/xxx/icons";
declare const SVG = "svg-file-icons";

declare interface MyIcons {
  "image/jpeg": string;
  "image/jpg": string;
}

export const FILE_ICONS_SVG: MyIcons = {
  "image/jpeg": `${S3}/${SVG}/jpg.svg`,
  "image/jpg": `${S3}/${SVG}/jpg.svg`
};

I want to include this object in a shared NPM Package for consistency across all my projects. However, during TSC compilation, I encounter the following output.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FILE_ICONS_SVG = {
    "image/jpeg": `${S3}/${SVG}/jpg.svg`,
    "image/jpg": `${S3}/${SVG}/jpg.svg`
};

It is clear that S3 and SVG are not defined in the compiled JavaScript file, resulting in errors upon usage.

What can be done to resolve this issue?

Answer №1

When using the declare keyword, it doesn't actually "declare" anything per se.

The purpose of declare is simply to inform the type-system that a certain name and type exist.

If you want to create a constant that exists outside of the type-system, meaning it should be present during runtime, you need to omit the declare keyword.

Items that are declared do not affect the runtime behavior.

Why was declare introduced?

Consider how the web operates - in an html file, various scripts can be included. These scripts may be standalone or interact with elements from other scripts.

In a scenario where one file assigns a value to the window, for example, and another file subsequently utilizes this object, TypeScript's type-system would have no knowledge of that object's presence. Hence, you use declare to notify the type-system about its existence.


Therefore, it's recommended to define constants like this:

const S3 = "https://s3.amazonaws.com/xxx/icons";
const SVG = "svg-file-icons";

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

Declaration of dependencies for NestJS must include dependencies of dependencies

I'm encountering an issue where NestJS is not automatically resolving dependencies-of-dependencies: I have created an AWSModule which is a simple link to Amazon AWS with only a dependency on the ConfigService: @Module({ imports: [ConfigModule], ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

The navigation bar is struggling to be positioned on top of the body

I have encountered an issue where I want my navbar to remain on top of all components, but when I open the navigation menu, it pushes all the components of the index page down. My tech stack includes Next.js, Tailwind CSS, and Framer Motion. This problem ...

Ways to display all utilized typescript types within a project

Here is a snippet of code I'm working with in my project: describe('Feature active', () => { it('Should render a Feature', () => { const wrapper = shallow(<MyComponent prop1={1}/>); expect(wrapper.prop('p ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Discovering the current date in Angular 8 by utilizing the form builder

Is there a way to automatically fill a form created with FormBuilder with the system's date and time when it is created, instead of the default date format? this.creationDate = moment().format(DATE_TIME_FORMAT); I want to update the creationDate fie ...

Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server: historyApiFallback: { index: 'index.html', } Now, when transitioning to production mode, I wanted to replicate the ...

TypeScript: "Implementing" methods. The organized approach

Currently, I am developing a middleware class for Express. Before delving into the details of the class, it's important to note that I will be injecting the middleware later by creating an instance of my "Authenticator" class and then using its method ...

JavaScript live search dynamically loads MySQL data into memory

Currently, I have implemented a live search feature through a text box on my website. This feature queries a MySQL database to return matching rows as the user types. However, I have noticed that this has significantly increased the memory load on my datab ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

Implemented rounded corners to the bar chart background using Recharts

I have been experimenting with creating a customized bar chart that includes border radius for the bars. While I was successful in adding border radius to the bars themselves, I am struggling to add border radius to the background surrounding the bars. Any ...

Notifications will be displayed with Alertifyjs to the individual who activated them

Just diving into the world of nodejs and express framework, so I appreciate your patience as I navigate through this learning process. I've implemented the alertifyjs library to display notifications for different alerts on my site. However, I&apos ...

When using ReactJS, hovering over a row in a table should trigger a change in the background color of the corresponding row in another table with the same index

I need to create a feature where hovering over a row in the first table will highlight a corresponding row in the second table. The highlighting should be based on the index of the hovered row. Here is an example: <div> <table> < ...

Understanding the implementation of setters in JavaScript: How are they utilized in Angular controllers?

After learning about getters and setters, I came across an example that clarified things for me: var person = { firstName: 'Jimmy', lastName: 'Smith' }; Object.defineProperty(person, 'fullName', { get: function() ...

Issue with Vue and Firebase: New users are being created successfully, but are being logged into existing user accounts

I've encountered a strange issue in Firebase. When I create a new user with the same password as an existing user, the new user is logged in under the previous user's account and displays all their information. However, upon logging out and signi ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...