What is the process for importing constants from a separate file in TypeScript?

Sorry for the novice question, but I'm trying to organize my code by moving all constants into a separate file and importing them. However, I can't seem to get it to work despite trying different methods. Most resources I've found online focus on importing classes and functions rather than constants.

In a file called constants.tsx, I have declared various constants:

export const default_bg               = "#2456a5"
export const default_light_font_color = "white"
export const default_lg_font_size     = 11
export const default_md_font_size     = 10
export const default_sm_font_size     = 9
export const default_dark_font_color  = "#000028"
export const default_font             = "arial"

In my main file with the functionality, App.tsx:

import * as React from 'react';
import { Header } from './Header';
import { Body } from './Body';

import * as defaults from 'constants'

...

However, when I try to access these constants using defaults.default_bg, I encounter this error message:

TS2339: Property 'default_bg' does not exist on type 'typeof import("constants")'.

Additionally, when I log defaults in the console, I see:

https://i.sstatic.net/CP0u5.png

This may be a simple issue, but as someone new to TypeScript and JavaScript, I am struggling to resolve it.

Answer №1

Utilize the import statement to access all values from 'constants'

This code snippet directs node to locate a module named 'constants' inside the /node_modules directory.

To modify this line, update it to:

import * as defaults from './path/to/constants'

The output displayed in the console may vary depending on what is assigned to the defaults variable.

Answer №2

Here is my current approach:

constants.ts

export const settings = {
    primaryColor: "#2456a5",
    lightFontColor: "white",
    largeFontSize: 11,
    mediumFontSize: 10,
    smallFontSize: 9,
    darkFontColor: "#000028",
    fontType: "arial"
} as const;

app.js

import { settings } from "./path/to/constants";
...
console.log('Primary Color: ', settings.primaryColor);

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

How come webstorm/react-hook-forms isn't showing me suggested choices for the "name" field?

I'm looking to create components with inputs, but I'm currently facing an issue with tooltips not showing for the name. I would like the form fields to display the name. export const Form: FormType = ({ children, form }) => ( <FormProvide ...

Issue: property is not accessible on the current object in Angular 5

When trying to access a property from the object, I encountered an error. The JSON format received from the server is as follows: { "result": false, "messages": "welcome", "data": [ { "name": "siva", "category": true, "count": ...

Displaying continuous hours on the X-Axis within a 24-hour time series using Recharts

I've been attempting to showcase server data on a scatter chart with multiple y axes, but I'm encountering issues with duplicate hours on the X axis: https://i.sstatic.net/Spd7u.png Here's the code snippet I have so far: <XAxis dataK ...

Leveraging functionality from an imported module - NestJS

Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS. Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't ...

Unable to employ a custom Typescript .d.ts file

Currently, I am delving into learning TypeScript and encountering a hurdle while attempting to define a class in a TypeScript definition file and then utilize it in a TypeScript file. The dilemma lies with a JavaScript "class" called "Facade," which serve ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

Creating a websocket handler template for universal use

Currently, I am exploring different approaches to handling a generic websocket handler. The current implementation of the handler I have looks something similar to this: type WSMessage = { type: string; [key: string]: unknown; } type HandlerFunc = ...

Improve the Precision of Return Types in Typescript by Specifying Targeted Signatures for Functions with Generic Parameters

I have the following types: interface AutosuggestState<Item> { highlightedIndex: number | null; inputValue: string | null; isOpen: boolean; selectedItem: Item | null; } interface ItemToString<Item> { (item: Item): string; } interfa ...

Step-by-step guide on adding a command to a submenu through the vscode extension api

I'm developing a Visual Studio Code extension and I want to include a command in a submenu like this https://i.stack.imgur.com/VOikx.png In this scenario, the "Peek" submenu contains commands such as "Peek Call Hierarchy". My current Package.json fi ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

What is the method for defining the type of a variable without assigning a value to it?

Working on an Angular 11 project using Typescript with Strict Mode, I encountered the following issue: export class AvatarComponent { @Input() user: UserModel = null; } This resulted in a compilation error: Type 'null' is not assignable to ty ...

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Incorporate a unique CSS class using a variable in the JSX that is returned

I have developed a unique component that generates HTML markup to display content based on the provided values. Below is a simplified version of the code: interface ContainerProps { position?: string; content?: string; className?: string; } co ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

Exploring the world of interfaces in nested mapping functions

Currently, I'm faced with the challenge of mapping an array inside another map with an array. These are the specific interfaces that I am working with: interface Props { columns: Array<{field: string, headerName: string, width: number}>; row ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

Cracking the Code: Demystifying TypeScript Syntax within Angular 4

Recently, I delved into the world of Angular 4 and Typescript by following the step-by-step "Angular-tour-of-heroes" tutorial on the Angular.io website. Since Angular 4 relies on typescript for defining components and more, I wanted to deepen my understand ...

What sets an Array apart from an Observable Array?

When working with TypeScript, how do any[] and Observable<any[])> differ from each other? What advantages and disadvantages does each one offer? ...

Struggling to retrieve an Object from an HTMLSelectElement within an Angular project

Can you help me with this code snippet: <select #categorySelect (change)="goToCategory.emit(categorySelect.value)" style="..."> <option selected hidden>All</option> <option [ngValue]="categ ...