TypeScript compilation error, importing non default interface with curly braces - node.js

When compiling my TypeScript project, the compiler is throwing the following error:
node_modules/#types/domutils/index.d.ts:6:10 - error TS2614: Module '"../../domhandler/lib"' has no exported member 'DomElement'. Did you mean to use 'import DomElement from "../../domhandler/lib"' instead?
The offending line is:
import { DomElement } from "domhandler";
The problem is, in the typing file it is trying to import from, the DomElement interface is a non default exported interface as follows:
export interface DomElement {
attribs?: {[s: string]: string};
children?: DomElement[];
data?: any;
name?: string;
next?: DomElement;
parent?: DomElement;
prev?: DomElement;
type?: string;
}
If I remove the curly braces it does in fact work, but that seems problematic to me:
I was under the impression that only default exports can be imported without curly braces. Why is this import required without curly braces?
This issue is occurring in type definitions in the node-modules folder as provided by DefinitelyTyped. I do not want to change a dependency file. There are no related open issues in Github, so I assume it does work. In fact it works for a colleague with an older version of Node (v8) but that doesn't seem like it should make a difference.
Versions:
Node.js - 12.14.0
List item
TypeScript 3.7.2 (also tested not working on 3.7.4)
Type definitions for domhandler 2.4 (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/domhandler)
Type definitions for domutils 1.7 (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/domutils)
UPDATE
Here is my tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*"
]
}
},
"include": [
"src/**/*"
]
}

Based on info from aluanhaddad at GitHub I managed to get it compiling (and working), though I don't like the solution (because it's actually turning any checking for that module off).
I have removed typings to sanitize-html (and related domhandler etc.). TSC cries that it doesn't know "sanitize-html" module, so I've added a dummy module declaration inside my src folder.
src/sanitize-html.d.ts
declare module 'sanitize-html';
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"lib": [
"es6",
"dom"
],
"include": [
"src/**/*",
"index.ts"
],
"exclude": [
"**/*.spec.ts"
]
}
build command:
tsc

Related

How to add shortcuts to modules in Nodejs Typescript

So we have a ReactTs project and we implemented shortcuts to things like our utils folder, So instead of calling the relative path everytime we use it in a module we just call #utils. We did this by adding path in our tsconfig.json.
This feature looks so handy and clean we decided to do the same on our Nodejs Typescript application. But when we compile the project and run the compliled js project it returns an error that seems #utils is not found. is there a way over this? How can we tell to compile the #utils to the declared relative path?
tsconfig file:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "./build",
"strict": true,
"baseUrl": "./",
"paths": {
"#interface": [
"interface/index.ts"
],
"#utils":[
"src/utils/index.ts"
]
},
"types": [
"node_modules/#types"
],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Project directory:
So to solve this I implemented this npm: https://www.npmjs.com/package/module-alias.

Nodejs Typescript type only package is not exporting all types properly

The package I'm building (https://github.com/plastikfan/xiberia/tree/develop) is a type only package (I'm not using DefinitelyTyped and this question is not about DT).
The package essentially is just a single file (index.ts) which contains various exported types such as:
export interface IYargsFailHandler {
(msg: string, err: Error, inst: yargs.Argv, command: any): yargs.Argv;
}
The problem is, when I use this in a client app, most of the types are missing and the only type that appears by intellisense is:
export const CoercivePrimitiveStrArray = ['boolean', 'number', 'symbol'];
All the other types are missing.
When I look at the corresponding index.js file, all it contains is:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoercivePrimitiveStrArray = ['boolean', 'number', 'symbol'];
// -----------------------------------------------------------------------------
//# sourceMappingURL=index.js.map
The generated index.d.ts looks correct and contains all the types, (well there is one very weird definition that I can't account for at the end of the file):
export {};
My typescript config file is:
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "Node",
"noImplicitAny": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es5",
"declaration": true,
"declarationDir": "./dist",
"outDir": "./dist",
"diagnostics": true,
"lib": [
"es5",
"es2015",
"es6",
"dom"
],
"types": [
"node", "yargs"
],
},
"include": [
"./index.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
So why are most of the types missing and how do I correct it, thanks.
EDIT: OOPS, I just made a really silly mistake. The types should not be in the resultant .js file. The only valid js is indeed the CoercivePrimitiveStrArrayCoercivePrimitiveStrArray which is being exported.
But that doesnt explain why the types that are being exported are not shown by intellisense on the clienbt side.
So on the client, this is what I have:
in a client file:
import * as xiberia from 'xiberia';
When I type, "xiberia.", I would expect to see all the types being exported, but I don't see any.
I read up on the triple slash directive and it appears they are not appropriate for this situation.
So what other config setting do i need for te intellisense to work as expected?
I fixed this problem by simplifying the package as much as possible. Previously, I was building artefacts into the 'dist' folder, a pattern which is widely used. I have removed this (this is a simple single file package, so using a dist folder is overkill) and simply build out the resultant index.d.ts, index.js and the .map files into the root directory. This also required explicity specifiying these files in the 'files' property in package.json (this ensures that these files are included in the resultant package tarball built when performing npm pack via the publish mechanism).
I don't understand why now intellisense is working as a result of these actions; perhaps somebody who knows better can comment.

Cannot find declaration file for 'autobind-decorator' in typescript

I am using Typescript and I want to import 'autobind-decorator' package inside project but ı stuck here.
I am getting this error line while compiling:
cannot find declaration file for 'autobind-decorator'. Implicitly has an 'any' type
I also tried #types/autobind-decorator npm package, but it didn't work.
Is there any option to get rid of this compile error ?
Here is my tsconfig:
{
"version": "2.1.5",
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "es2016", "dom"],
"sourceMap": true,
"noImplicitAny": true,
"target": "es6",
"jsx": "react",
"skipLibCheck": true,
"experimentalDecorators": true
},
"include": [
"./packages/ld-web/src/**/*"
],
"exclude": [
"**/node_modules",
"**/*.d.ts"
]
}
import :
import * as autobind from "autobind-decorator";
From the type declarations here it declares and exports as module,
You need to install the #types as:
npm install #types/autobind-decorator --save-dev
and import as:
import autobind = require("autobind-decorator");
This worked, not using import at all:
const { autobind } = require('autobind-decorator');
I still had errors at runtime, so I read the doc again
https://www.npmjs.com/package/autobind-decorator
and used
const { boundMethod } = require('autobind-decorator');
that works,
I tried again using import and it failed.

How do I figure out all the global imports and from where are those imported?

when I add the following line at the beginning of app.ts
const crypto = require('crypto');
I get the following error,
Cannot redeclare block-scoped variable 'crypto'
Seems like it has been globally imported from somewhere else,
this is how my tsconfig.json looks like
{
"compilerOptions": {
"allowJs": true,
"outDir": "./dist",
"target": "ES6",
"module": "commonjs",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"strictNullChecks": true,
"noUnusedLocals": true,
"types": [
"node"
],
"typeRoots": [
"./node_modules/#types"
],
"lib": ["es2015", "dom"]
},
"include": [
"./src/"
]
}
PS:
The above error is when I try to transpile it from terminal.
I am using VisualStdioCode, in VisualStdioCode it doesn't show any error as it points to,
/path/to/VisualStdioCode/Visual Studio
Code.app/Contents/Resources/app/extensions/typescript/node_modules/typescript/lib/lib.dom.d.ts
EDIT(solved):
The problem here was slightly different than cannot redeclare block scoped variable (typescript)
The aim of this question was to detect duplicate import source than use ES6 non explicit assignment to atomatically solve it for us.
The solution here was to import either from libs or node_modules and not to scope it unlike mentioned in answers there.
crypto is already a global read-only property in the browser, so TypeScript is keeping you from trying to overwrite it.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
But since you're using commonJS, you may be building for Node and maybe you didn't mean to include the "dom" typings in "lib"?

Error importing node modules in TypeScript

I had a problem this morning that was driving me crazy. I'll explain the issue and then I'll provide my answer below (so that others who come across this can get to a solution sooner).
It is very easy to duplicate the issue by just issuing these commands:
tsd query react --action install
mkdir src
echo "import React = require('react');" > src/foo.ts
I also included the following tsconfig.json file in src:
{
"version": "1.6.2",
"compilerOptions": {
"outDir": "./tsdir",
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"isolatedModules": false,
"jsx": "react",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true
},
"files": [
"foo.ts"
]
}
If I try to compile this by simply running the tsc (version 1.6.2) command inside src, I get:
foo.ts(1,24): error TS2307: Cannot find module 'react'.
What I find baffling here is that I've installed the react bindings with tsd but when I run tsc, I get this error. It looks like I've done everything right, so why the error?
So what I eventually figured out was that I need to explicitly include the typings file in my list of "files", i.e.,
{
"version": "1.6.2",
"compilerOptions": {
...
},
"files": [
"foo.ts",
"../typings/react/react.d.ts"
]
}
In other words, I had to include the typings files explicitly in the "files". I don't really know why. I thought tsc was smart enough to look for them itself.
If there is a better solution that doesn't involve having to list all the .d.ts files explicitly in "files", I'm all ears. But I just wanted to point out that this is at least a workaround.

Resources