How to import a js library without definition file in typescript file - javascript

I want to switch from JavaScript to TypeScript to help with code management as our project gets larger. We utilize, however, lots of libraries as amd Modules, which we do not want to convert to TypeScript.
We still want to import them into TypeScript files, but we also do not want to generate definition files. How can we achieve that?
e.g. The new Typescript file:
/// <reference path="../../../../definetelyTyped/jquery.d.ts" />
/// <reference path="../../../../definetelyTyped/require.d.ts" />
import $ = require('jquery');
import alert = require('lib/errorInfoHandler');
Here, lib/errorInfoHandler is an amd module included in a huge JavaScript library that we do not want to touch.
Using the above code produces the following errors:
Unable to resolve external module ''lib/errorInfoHandler''
Module cannot be aliased to a non-module type.
This should actually produce the following code:
define(["require", "exports", "jquery", "lib/errorInfoHandler"], function(require, exports, $, alert) {
...
}
Is there a way to import a JavaScript library into TypeScript as an amd Module and use it inside the TypeScript file without making a definition file?

A combination of the 2 answers given here worked for me.
//errorInfoHandler.d.ts
declare module "lib/errorInfoHandler" {
var noTypeInfoYet: any; // any var name here really
export = noTypeInfoYet;
}
I'm still new to TypeScript but it looks as if this is just a way to tell TypeScript to leave off by exporting a dummy variable with no type information on it.
EDIT
It has been noted in the comments for this answer that you can achieve the same result by simply declaring:
//errorInfoHandler.d.ts
declare module "*";
See the github comment here.

Either create your own definition file with following content:
declare module "lib/errorInfoHandler" {}
And reference this file where you want to use the import.
Or add the following line to the top of your file:
/// <amd-dependency path="lib/errorInfoHandler">
Note: I do not know if the latter still works, it's how I initially worked with missing AMD dependencies. Please also note that with this approach you will not have IntelliSense for that file.

Create a file in lib called errorInfoHandler.d.ts. There, write:
var noTypeInfoYet: any; // any var name here really
export = noTypeInfoYet;
Now the alert import will succeed and be of type any.

Typically if you just want to need a temporary-faster-solution, that could be done by defining a new index.d.ts in the root of the project folder, then make a module name like described inside package.json file
for example
// somefile.ts
import Foo from '#awesome/my-module'
// index.d.ts on #awesome/my-module
declare module '#awesome/my-module' {
const bind: any;
export default bind;
}

Ran into that that problem in 2020, and found an easy solution:
Create a decs.d.ts file in the root of your TS project.
Place this declaration:
declare module 'lib/errorInfoHandler';
This eliminates the error in my case. I'm using TypeScript 3.9.7

Related

How can I use all import, modules.export, and export in the same ts file?

I have a typescript file in which there are some functions for validating objects of different classes. So, I have to import those classes into the ts file. For instance,
import { UserDetail } from "../../entity/user/userDetail";
The following block of code depicts a function which is used for validating the objects of the mentioned class.
export function validateSignUpData(userDetail:UserDetail):Array<String>{
let errorMessages = new Array<String>();
/* Some Code */
As you can see the imported class has been used as the function's input type. Now the problem is that it seems we are not allowed to use both import and module.exports simultaneously! Therefore, I am not able to use require in order to get the mentioned function in the Node server file.
When I add the following block of code to my ts file, the following exception is thrown!
module.exports = validateSignUpData;
TypeError: Cannot assign to read only property 'exports' of object '# object'
Question: How can I use all import, modules.export, and export in the same ts file?
I will be glad if someone can help me with the situation.
Thank You
Of course you're able to import that function with require. Just do it like this:
const {validateSignUpData} = require('./my-module.js')
And pay attention to require the compiled javascript file, not the typescript file. They may be in different folders, depending on your build setup.

TypeScript declarations for JavaScript module

I recently started using a Node library called bpmn-js (npmjs.com).
It is written in JavaScript, and I'd like to have typings. Thus, I've began reading about d.ts files.
I created this folder structure
webapp
#types
bpmn-js
index.d.ts
With a simple content
declare module 'bpmn-js' {
export class BpmnJS {
constructor();
}
}
But this doesn't seem to work.
"Before" typings, I was able to import the object I needed using
import BpmnJS from 'bpmn-js';
And I was able to instantiate it using
new BpmnJS();
How can I get the typings file to be recognized?
I'm using WebStorm 2019.1.*.
Pretty simple, I was missing export default, or better, the default part.
declare module 'bpmn-js' {
export default class BpmnJS {
constructor(param?: { container: string });
...
}
}
Now this works too
import BpmnJS from 'bpmn-js';

Import JS web assembly into TypeScript

I'm trying to use wasm-clingo in my TypeScript React project. I tried to write my own d.ts file for the project:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
export const Module: any;
}
and import like this:
import { Module } from 'wasm-clingo';
but when I console.log(Module) it says undefined. What did I do wrong?
Notes:
clingo.js is the main js file.
index.html and index_amd.html are two example pages
Solution:
I solved the problem like this:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
const Clingo: (Module: any) => Promise<any>;
namespace Clingo {}
export = Clingo;
}
and
import * as Clingo from 'wasm-clingo';
Here's the source for this solution
I know you found a solution acceptable to you; however, you don't really have any types here, you just have Module declared as any, which gives you no typescript benefits at all. In a similar situation I used #types/emscripten, which provides full type definitions for web assembly modules compiled using emscripten. You simply need to do:
npm install --save-dev #types/emscripten
then change your tsconfig.json types array to add an entry for emscripten.
After that you can just write Module.ccall(...) etc. If you like you could of course write const Clingo = Module and then make calls against that if you want a more descriptive name than Module (which is a terrible name!).
You're welcome ;)
I think the issue is that wasm-clingo exports the module itself but import { Module } from 'wasm-clingo' expects a property.
Try
import Clingo_ from 'wasm-clingo';
const Clingo: typeof Clingo_ = (Clingo_ as any).default || Clingo_;

How do we declare import types from NPM library that has no declaration files?

For example, if I have the following in my app,
import Node from 'infamous/motor/Node'
console.log(Node)
that works just fine. But the moment I actually do something with it,
import Node from 'infamous/motor/Node'
console.log(new Node)
then TypeScript will complain because there's no type definition for Node. How do I define the type of Node?
The library has no type declarations of it's own. I tried something like
import MotorNode from 'infamous/motor/Node'
declare class MotorNode {}
console.log(' --- ', new MotorNode)
but I get the error
./src/app.tsx(6,8): error TS2440: Import declaration conflicts with local declaration of 'MotorNode'
When I need to do what you are trying to do, I create an externals.d.ts file in which I put module augmentations for my project and make sure that my tsconfig.json includes it in the compilation.
In your case the augmentation might look something like this:
declare module "infamous/motor/Node" {
class Node {
// Whatever you need here...
}
export default Node;
}
I put it in a separate file because a module augmentation like this has to be global (must be outside any module), and a file that contains a a top-level import or export is a module. (See this comment from a TypeScript contributor.)

TypeScript - Module is undefined at runtime

I dont understand what i'm doing wrong. I've create a TypeScript project in VS2012, and created a file named "Vector.ts", in a sub-directory named "Physics":
// Module
module Physics {
// Class
export class Vector {
constructor(public x: number) { }
}
}
Also, I have the following app.ts file:
/// <reference path="Physics/Vector.ts" />
window.onload = () => {
var vector = new Physics.Vector(6);
};
The project is successfully compiled, but when i launch it, i get the following exception:
0x800a1391 - JavaScript runtime error: 'Physics' is undefined
I don't understand what am i doing wrong...
Thanks.
If you are using AMD style modules with a module loader such as Require.Js, you need an import statement. See Steve's accepted answer here: https://stackoverflow.com/a/14919495/1014822 Your code will look something like:
import Physics = module("Physics/Vector");
var vector = new Physics.Vector(6);
... and you won't need this: /// <reference path="Physics/Vector.ts" />
If you are not using a module loader, you just need to make sure you include your Vector.js output file somewhere in your html page, and make sure it loads before your app file. In this case, you use /// <reference path="Physics/Vector.ts" /> to tell TS where to find your module for intellisense etc. to work.
Just for completeness, if you're using System then you'd use the import function:
System.import("Physics/Vector");
If you're doing this for Angular 2 then you'd want to do this before your bootstrap import

Categories

Resources