Using global from different modules - javascript

I have a modular project, where the main module (entrypoint) is written in javascript, meanwhile some auxiliary libs are in typescript.
The javascript module, when starts, assign some set of variables, using global.
The problem is I don't to share this variables with the typescript libs.
It runs, but I'm getting some error when publishing:
Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
The javascript set these variables as below:
static loadProperties() {
global.myProperties = new Map();
global.myProperties.set('SOME_VARIABLE', 'someValue');
}
The typescript lib uses it as following:
const someVariable: string = global.myProperties.get('SOME_VARIABLE');
But when running the npm run compile command, throws the exception mentioned before.

since you global really don't have any such attribute
I really don't recommend using global. but if you want to, here's how:
global.d.ts:
declare namespace NodeJS {
export interface Global {
myProperties: Map<unknown, unknown>
}
}
// and / or top-level module
declare var myProperties: Map<unknown, unknown>
In addition, your code has a syntax error:
static loadProperties() {
global.myProperties = new Map();
// global.myProperties.set('SOME_VARIABLE') = 'someValue';
global.myProperties.set('SOME_VARIABLE', 'someValue');
}

Related

Typescript to Javascript export

I have a sample typescript objects as
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 am declaring this object in a share NPM Package to maintain consistency in all my projects. But TSC compilation gives me something like this.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FILE_ICONS_SVG = {
"image/jpeg": `${S3}/${SVG}/jpg.svg`,
"image/jpg": `${S3}/${SVG}/jpg.svg`
};
As it is evident that S3 and SVG are not defined in the compiled js file and thus gives errors on usage.
How can this be fixed??
Using declare does not really "declare" something.
declare is only used to tell the type-system that something with the declared name and type exists.
If you want to define a constant that should exist outside of the type-system, aka exist at runtime, you have to remove the declare keyword.
declare'd things do not have any impact on the runtime
Why does declare exist?
If you think about how the web works, you have a html file. In that html you can include scripts. Those scripts may be completely independent from one another, but also use stuff from other scripts.
So if you have one file that attaches something to the window for example in one file, and have another file that then uses this object, the typescript type-system has no way of knowing that that object exists, so you can tell the type-system of its existence by using declare
So it should be
const S3 = "https://s3.amazonaws.com/xxx/icons";
const SVG = "svg-file-icons";

How can I reference a type in lib.dom.d.ts in another declaration file?

I'm pretty new to TypeScript and trying to make automated tests where I dependency-inject IndexedDB into my code, but the library I'm using to mock IDB doesn't have a .d.ts, so I tried to roll my own simple declaration file to get around this, which looked something like this:
declare let fakeIndexedDB: IDBFactory;
declare module 'fake-indexeddb' {
export var fakeIndexedDB;
}
However, when I tried using this type, I got the error:
type 'typeof import("fake-indexeddb")' is missing the following properties from type 'IDBFactory': cmp, deleteDatabase, open
Mousing over in VSCode, it looks like the type of IDBFactory is this type from lib.dom.d.ts:
declare var IDBFactory: {
prototype: IDBFactory;
new(): IDBFactory;
};
But what I wanted to import was the interface type directly above it. How would I say in my declaration file that I want to reference the interface in lib.dom.ts, not the var that uses it? I can see that jsdom was able to make a class in their .d.ts that references DOM types with both an interface and var, but they also don't use "declare module".
Problem
The problem with this code:
declare let fakeIndexedDB: IDBFactory;
declare module 'fake-indexeddb' {
export var fakeIndexedDB;
}
is that the type of the exported fakeIndexedDB is any. It's a different variable than the one declared above it. Basically, fake-indexeddb defined like that is a module that exports a single variable called fakeIndexedDB of unspecified type.
Solution
What you should do instead is this:
declare module 'fake-indexeddb' {
const fakeIndexedDB: IDBFactory;
export = fakeIndexedDB;
}
Whether to use export =, export or export default depends on how the actual JavaScript library is built. The above syntax is recommended if fake-indexeddb exports a single member and it's meant to work well when imported using the require function. See if it works, and if not, consult the source code.

Can`t extend the JavaScript native method declaration when use TypeScript

I try to extend JS native String class adding the new method but get TS2339 error.
interface String {
transl(): string;
}
String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'String'.
return 'xxx';
};
'ff'.transl();
Your code is technically correct, and works in the TypeScript playground, which leads me to believe that the problem is being caused by having this code inside of a module.
When you write an interface within a module, or namespace, it contributes to the naming context of that module or namespace. i.e. you may well be adding a new interface named String to your local naming context, rather than merging your interface declaration with the global String interface.
You can fix this by placing your interface in the global context, so it has the same common root as the one from the lib.d.ts file. Or using declare global from within a module:
declare global {
interface String {
transl(): string;
}
}
String.prototype.transl = function () {
return 'xxx';
};
'ff'.transl();

Node.js global variable and TypeScript

I need to have some strongly-typed global variables.
As mentioned here: Extending TypeScript Global object in node.js, in order to add fields to the global variable I need to add a .d.ts file that extends the Global interface that's specified in node.d.ts.
Also, as Basarat mentioned:
Your file needs to be clean of any root level import or exports. That
would turn the file into a module and disconnect it from the global
type declaration namespace.
Now, I need to have fields on the Global interface whose types are custom interfaces that I created:
declare namespace NodeJS{
interface Global {
foo: Foo
bar: Bar
}
}
I'm extremely not willing to use the any type.
I can move/copy all the interface declarations to this declaration file, but it's a bad solution for me, since both Foo and Bar in turn, aggregate many fields of other interfaces, including third party interfaces like Moment etc.
I need a solution for this paradox
Here's an approach. I don't know if this is the 'correct' way of doing things, but it works for me with TypeScript 3.7.4.
Assuming your source files live in a folder src, create a new folder src/types and create a file global.d.ts in this folder.
Author your declarations using one of the following strategies:
If you need to import external types into your declaration file, use the following syntax:
import { Express } from 'express';
declare global {
namespace NodeJS {
interface Global {
__EXPRESS_APP__: Express;
}
}
}
If your declaration file does not contain any imports, the above will not work, and you'll need to use this syntax instead:
declare namespace NodeJS {
interface Global {
__CONNECTION_COUNT__: number;
}
}
Make sure your global.d.ts file (and any other files you might add to src/types) is picked up by the TypeScript compiler, by adding the following to your tsconfig.json file:
{
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
}
Use the global variable as normal inside your code.
// Below, `app` will have the correct typings
const app = global.__EXPRESS_APP__;
I found this works.
Have one file that declares the property on the NodeJS.Global interface with the any type. This file has to be clean of imports or refrences.
node.d.ts
declare namespace NodeJS{
interface Global {
foo: any
}
}
Then in the second file you declare a global variable that has the correct type.
global.d.ts
import IFoo from '../foo'
declare global {
const foo:Ifoo
}
This worked for me (node v16.13.2)
In your root create file types/global.d.ts
declare global {
var __root: string
}
export {}
Note that __root declared with var keyword. It works with let and const too, but in this case __root will have any type. I don't know why;) If someone can explain this it will be great.
Configure your tsconfig.json
{
"compilerOptions": {
"typeRoots": [
"types"
],
}
}
Use declared variable in your code
// app.ts (entry point)
import path from 'path'
global.__root = path.join(__dirname)
// anyFileInProject.ts
console.log(__root) // will display root directory

Duplicate identifier error with d.ts file and nodejs require with same name

Now I am sure the issue is because there is a d.ts file included which contains a module called "Shared", and a require statement which includes a variable of the same name if it is being used in a NodeJS environment.
// shared.d.ts
declare module Shared { ... }
// other_module.ts
/// <reference path="shared.d.ts"/>
if(require) { var Shared = require("shared"); }
export class Something {
public someVar = new Shared.SomethingElse("blah");
}
So when I compile other_module.ts (which is actually a lot of separate files), it tells me Shared is a duplicate identifier, which I can understand as TS thinks Shared is a module, but then is being told it is the return of require.
The problem here is that the output of modules need to be compatible with nodeJS's require system, so in this case when other_module is required it will be in its own scope and will not know about Shared.SomethingElse so the require is needed so the internal modules in other_module will be able to access the Shared library, but in the browser environment it would get Shared.SomethingElse via the global scope.
If I remove the reference then the file wont compile as it doesn't know about Shared, if I remove the require when the module is loaded into nodejs (var otherModule = require("other_module")) it will complain that it doesn't know about Shared. So is there a way to solve this?
First the error
Duplicate identifier because you have Shared in shared.d.ts + in other_module.ts.
FIX A, be all external
If you want to use amd / commonjs ie. external modules, you need to use import/require (not var/require like you are doing). Using an import creates a new variable declaration space and therefore you are no longer polluting the global namespace Shared from other_module.ts. In short :
// shared.d.ts
declare module Shared {
export function SomethingElse(arg:string):any;
}
declare module 'shared'{
export = Shared;
}
And a typesafe import:
// other_module.ts
/// <reference path="shared.d.ts"/>
import Shared = require("shared");
export class Something {
public someVar = new Shared.SomethingElse("blah");
}
FIX B, as you were, but you need to use a different name then
Inside other_module don't use the name Shared locally if local scope is global scope. I recommend you just use external everywhere and compile for node with commonjs and browser with amd as shown in fix A, but if you must here is a compile fixed other_module.ts.
// other_module.ts
/// <reference path="shared.d.ts"/>
var fooShared: typeof Shared;
if(require) { fooShared = require("shared"); }
else { fooShared = Shared; }
export class Something {
public someVar = new fooShared.SomethingElse("blah");
}

Categories