Home > Back-end >  Global Variable typescript/ javascript
Global Variable typescript/ javascript

Time:12-15

I want to declare a global variable with default value

const Months = [
{ name: 'January' },
{ name: 'February' },
{ name: 'March' },
{ name: 'April' },
{ name: 'May' },
{ name: 'June' },
{ name: 'July' },
{ name: 'August' },
{ name: 'September' },
{ name: 'October' },
{ name: 'November' },
{ name: 'December' }
];

and i want to use the Months Variable in multiple files. without redeclaring it again. file1.tsx Months.map(x => x.name);

file2.tsx Months.map(x => x.name);

how im going to do it?

CodePudding user response:

Avoiding global variables can help to reduce bugs in your program and make your code easier to understand.

and i want to use the Months Variable in multiple files. without redeclaring it again.

This is exactly what is addressed by JavaScript modules, using the export and import keywords:

./constants.ts:

export const months = [
  { name: 'January' },
  { name: 'February' },
  { name: 'March' },
  { name: 'April' },
  { name: 'May' },
  { name: 'June' },
  { name: 'July' },
  { name: 'August' },
  { name: 'September' },
  { name: 'October' },
  { name: 'November' },
  { name: 'December' },
] as const;

./another_module.ts:

import { months } from './constants.js';

console.log(months.map(obj => obj.name)); // ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

CodePudding user response:

add this code to your run file (I think it's called main.ts )

window.Months = [
{ name: 'January' },
{ name: 'February' },
{ name: 'March' },
{ name: 'April' },
{ name: 'May' },
{ name: 'June' },
{ name: 'July' },
{ name: 'August' },
{ name: 'September' },
{ name: 'October' },
{ name: 'November' },
{ name: 'December' }
];

and global.d.ts

declare var Months: { name: string }[]
  • Related