JSZip produces TS2322 error in node.js using typescript - node.js

After adding the import statement:
import JSZip from 'jszip';
The build will produce an error:
TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
For these lines of code:
const env: string = process.env.NODE_ENV;
...
private timeoutTime: number = process.env.VUE_APP_TIME_OUT;
...
node.js version: 14.16.1
jszip version: 3.7.1
typescript: 3.9.4
Removing the import for JSZip the error goes away.
There are multiple instances of this same error - but not in every case where process.env is used.
Not sure how to resolve this.

the properties in process.env have a type string | undefined you have two options
first
cast them props to yow desired type
const env = process.env.NODE_ENV as string;
second
create a file call types.d.ts at yow package.json add a prop call types and set the path to yow new file types.d.ts
{
....
"types":"./types.d.ts",
....
}
in yow tsconfig.json there is a prop call typeRoots assuming yow "baseUrl": "./node_modules"
yow typesRoots will look like:
//tsconfig.json
{
"baseUrl": "./node_modules",
"typeRoots": [
"../types.d.ts",
]
}
add this to the new file
/// <reference types="node" />
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: "development" | "production" | "test";
readonly PUBLIC_URL: string;
readonly PORT: string;
}
}
Now add all yow vars there all them vars you set there will have a type string

Related

Typescript compiling errors using 'vss-web-extension-sdk' & 'azure-pipelines-task-lib'

I am trying to follow the following guide to make a custom task in azure devops https://learn.microsoft.com/en-us/azure/devops/extend/develop/add-build-task?view=azure-devops
When I install both 'azure-pipelines-task-lib' & 'vss-web-extension-sdk'
and have a single typescript file that requires the task-lib, like the guide suggests, I get tons of typescript errors.
package.json
"dependencies": {
"azure-pipelines-task-lib": "^3.1.9",
"typescript": "^4.4.3",
"vss-web-extension-sdk": "^5.141.0"
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es6",
"rootDir": "src/",
"outDir": "dist/",
"types": [
"vss-web-extension-sdk"
]
},
"files": [
"src/index.ts"
]
}
index.ts
import tl = require('azure-pipelines-task-lib/task');
export function Foo() {
return "BAR"
}
File structure
Root
tsconfig.json
package.json
src
index.ts
dist
index.js
Errors
https://imgur.com/4aNJetK
node_modules/#types/node/module.d.ts:2:5 - error TS2300: Duplicate identifier 'mod'.
2 export = NodeJS.Module;
~~~~~~~~~~~~~~~~~~~~~~~
node_modules/#types/requirejs/index.d.ts:38:14
38 export = mod;
~~~
'mod' was also declared here.
node_modules/#types/requirejs/index.d.ts:38:14 - error TS2300: Duplicate identifier 'mod'.
38 export = mod;
~~~
node_modules/#types/node/module.d.ts:2:5
2 export = NodeJS.Module;
~~~~~~~~~~~~~~~~~~~~~~~
'mod' was also declared here.
node_modules/#types/requirejs/index.d.ts:422:13 - error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type
'NodeRequire', but here has type 'Require'.
422 declare var require: Require;
~~~~~~~
node_modules/#types/node/globals.d.ts:213:13
213 declare var require: NodeRequire;
~~~~~~~
'require' was also declared here.
node_modules/vss-web-extension-sdk/typings/vss.d.ts:3168:13 - error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'Require'.
3168 declare var require: Require;
~~~~~~~
node_modules/#types/node/globals.d.ts:213:13
213 declare var require: NodeRequire;
~~~~~~~
'require' was also declared here.
Can someone provide me with ANY working example of compiling typescript when these libraries are installed?

Using Nipplejs in Vue with Quasar

i am trying to use Nipplejs in my Vue Project with quasar Components.
I installed nipplejs by npm install nipplejs --save.
I tried to integrate the nipple with the following code:
<template>
<div id="joystick_zone"></div>
</template>
<script lang= "ts">
// Imports
import Vue from "vue";
import nipplejs from 'nipplejs';
export default Vue.extend({
async mounted(): Promise<void> {
var options = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: `'blue'`,
}
var manager = nipplejs.create(options);
}
});
My first problem is that typescript doesnt accept 'static' as mode:
The definition says: mode?: 'dynamic' | 'semi' | 'static';
And i get the following error message:
Argument of type '{ zone: HTMLElement; mode: string; color: string; }' is not assignable to parameter of type 'JoystickManagerOptions'.
Types of property 'mode' are incompatible.
Type 'string' is not assignable to type '"dynamic" | "semi" | "static" | undefined'.
My second problem is that the joystick does not appear on the website.
If someone could help i would be very thankful.
If you would look into the definition of options variable you created. You would see it is of type { zone: HTMLElement; mode: string; color: string; }.
You must assign a type to the options variable.
var options: JoystickManagerOptions = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: 'blue',
};
Other option is to define the variable as const:
var options = {
zone: document.getElementById('joystick_zone') as HTMLElement,
mode: 'static',
color: 'blue',
} as const;
// Variable is now of type
type options = {
zone: HTMLElementHTMLElement;
mode: 'static';
color: 'blue';
}

exports is not defined when running compiled typescript

I am trying to take my first steps into working with typescript and I've run into an issue when trying to run my application.
I get the error ReferenceError: exports is not defined
the code I have is quite simple:
// --src/changeset.ts
export enum ChangeAction {
ADD,
DELETE,
MODIFY
}
export class Changeset {
constructor(
public version: Number,
public content: String,
public path: String,
public action: ChangeAction
) {}
}
// --src/index.ts
import { Changeset, ChangeAction } from "./changeset";
const set = new Changeset(0, "Hello world", "/dev/null", ChangeAction.ADD);
set.version = 0;
console.log("Hello World! " + set.version);
// --tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "build"
},
"include": ["src/**/*"]
}
running tsc, it compiles and seems to work without any real issues, however when I try to run it with node build/index.js it crashes with this
build/index.js:2
Object.defineProperty(exports, "__esModule", { value: true });
^
ReferenceError: exports is not defined
It feels like I am missing something quite obvious, but I can't really seem to put my finger on it, so what am I missing?
You appear to have enabled Node's ES modules by setting "type": "module" in your package.json, but your tsconfig tells typescript to emit code compatible with CommonJS.
Either remove "type": "module", or configure tsconfig to emit code targeting ES modules.

TS2451: Cannot redeclare block-scoped variable 'custom'

I'm using typescript in a web project. I use awesome-typescript-loader as a webpack loader. I am getting error when building my project:
ERROR in [at-loader] ./node_modules/#types/node/index.d.ts:82:15
TS2451: Cannot redeclare block-scoped variable 'custom'.
ERROR in [at-loader] ./node_modules/#types/node/index.d.ts:85:15
TS2451: Cannot redeclare block-scoped variable 'custom'.
ERROR in [at-loader] ./node_modules/#types/node/ts3.2/util.d.ts:7:15
TS2451: Cannot redeclare block-scoped variable 'custom'.
ERROR in [at-loader] ./node_modules/#types/node/ts3.2/util.d.ts:10:15
TS2451: Cannot redeclare block-scoped variable 'custom'.
I initiated a complete new folder with just typescript and #types/typescript installed, I can still see the same error complained by visual studio code.
Versions below:
"dependencies": {
"#types/node": "^11.13.6",
"typescript": "^3.4.4"
}
As the error showed above, I found
in index.d.ts:
declare module "util" {
namespace inspect {
const custom: symbol;
}
namespace promisify {
const custom: symbol;
}
namespace types {
function isBigInt64Array(value: any): boolean;
function isBigUint64Array(value: any): boolean;
}
}
in util.d.ts:
declare module "util" {
namespace inspect {
const custom: unique symbol;
}
namespace promisify {
const custom: unique symbol;
}
namespace types {
function isBigInt64Array(value: any): value is BigInt64Array;
function isBigUint64Array(value: any): value is BigUint64Array;
}
}
We can see custom is indeed being re-declared in index.d.ts and util.d.ts.
So my question is how to fix this issue? Is this a bug of #types/node?
I was facing the same issue. Removing reference to node in tsconfig fixed the issue for me.
Sample tsconfig.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"sourceMap": true
},
"files": [
// "./node_modules/#types/node/index.d.ts",
"./node_modules/#types/express/index.d.ts"
],
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
],
"lib": [
"es2017"
]
}
My problem is that I accidentally included node_modules/#types. Fixed by comment it out like this:
"include": ["src/**/*.ts","__tests__/**/*.ts"/*, "node_modules/#types"*/]
I had the same issue, but the error message was misleading just because of something wrong cached. I tried many things, but finally solved it by removing npm_modules, clearing cache, and new installation:
npm cache clean --force
npm install
I added this piece of code twice in protractor.conf.js file
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.e2e.json')
});

Generated definition file (.d.ts) by typescript not working with package.json typings

I have created a definition file (d.ts) from my typescript project using the --declaration argument from the tsc compiler.
But this generated definition file apparently not work when i try to publish the package with the property typings at the npm package.json. I have created another project to test it.
It complains with the message: "Exported external package file typings file '...d.ts' is not a module. Please contact the package author to update the package definition".
This are my source files:
MyInterface.ts
export interface MyInterface
{
MyProperty: string;
}
MyClass.ts
import {MyInterface} from './MyInterface';
export class MyClass implements MyInterface
{
get MyProperty(): string
{
return "MyString";
}
}
MyInheritedClass.ts
import {MyClass} from './MyClass';
export class MyInheritedClass extends MyClass
{
public MyMethod(): number
{
return 1;
}
}
The tsc command is this:
tsc MyClass.ts MyInterface.ts MyInheritedClass.ts --declaration -t es5 -outFile "mydefinition.js" --module "system"
This is the generated definition:
mydefinition.d.ts
declare module "MyInterface" {
export interface MyInterface {
MyProperty: string;
}
}
declare module "MyClass" {
import { MyInterface } from "MyInterface";
export class MyClass implements MyInterface {
MyProperty: string;
}
}
declare module "MyInheritedClass" {
import { MyClass } from "MyClass";
export class MyInheritedClass extends MyClass {
MyMethod(): number;
}
}
Is there another thing i have to do or the generated definition supposedly not work in the package.json typings ??
Update for more details:
The scenario is that i have 2 projects:
The First project is where i generate the library where i will publish to npm, and the package.json is where i put the typings property linking to the mydefinition.d.ts file generated by the tsc -d command.
The Second project i create to test the first one by adding the package (with typings) generated.
A link with the 2 projects and another links for the scenario :
https://github.com/jvitor83/typings-packagejson
I think the problem is with the "Your definition files should be written as external modules" at the first link.
But i want to know if there is a way to get those definitions generated to put at the typings property of the package.json.
To reproduce the problem:
Clone this repo: https://github.com/jvitor83/test-typings-packagejson
Do 'npm install', open with VSCode and go to the file 'src/test.ts'.
The solution was:
1 - add a single file 'index.ts' that exports all others files.
export * from "./MyInterface"
export * from "./MyClass"
export * from "./MyInheritedClass"
2 - add at build process two compilation/transpilation of the files (one for declarations and another for the single js file [with out property in tsc compiler])
let tsConfigDeclaration = gulp_typescript({module: 'system', target: 'es5', declaration: true, removeComments: true });
let tsConfigOneFile = gulp_typescript({module: 'system', target: 'es5', declaration: true, removeComments: true, out: 'typings-packagejson.js'});
More info at build process: https://github.com/jvitor83/typings-packagejson/blob/master/gulpfile.js
and index file: https://github.com/jvitor83/typings-packagejson/blob/master/app/src/typings-packagejson.ts
When are you getting this error?
I used the generated d.ts file in another project and is working fine.
/// <reference path="mydefinition.d.ts" />
import { MyInterface } from "MyInterface";
import { MyClass } from "MyClass";
import { MyInheritedClass } from "MyInheritedClass";
let x: MyInterface = { MyProperty: "hello!!" };
let y: MyClass = new MyClass();
let z: MyInheritedClass = new MyInheritedClass();
And on compiling it is generating JS file,
/// <reference path="mydefinition.d.ts" />
"use strict";
var MyClass_1 = require("MyClass");
var MyInheritedClass_1 = require("MyInheritedClass");
var x = { MyProperty: "hello!!" };
var y = new MyClass_1.MyClass();
var z = new MyInheritedClass_1.MyInheritedClass();
Are you getting this error when using this in some HTML file? Have you included the mydefinition.js file in the HTML?
Update
Based upon your more details, Here is the solution I may propose,
Add another file named index.ts and export all your modules from there,
index.ts
export * from "./MyInterface"
export * from "./MyClass"
export * from "./MyInheritedClass"
Add a tsconfig.json file for easy building,
tsconfig.json
{
"version": "1.0.0",
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"declaration": true,
"outDir": "lib/"
}
}
Note I have made it a commonjs module (not sure if it works for your need), generate build using tsc command. It will generate files like below note it has added js files for all ts files and d.ts is also for all module, But since we have exported all module from single file it will be easier to use in package.json file for npm module.
Then add package.json in the npm module you want to publish like below, let us consider module name is foo
package.json
{
"name": "foo",
"author": "author name",
"version": "1.0.0",
"main": "lib/index.js",
"typings": "lib/index.d.ts"
}
Now add the foo folder inside node_module, final structure for the second project will be something like below,
Finally in your test.ts file import and use,
test.ts
import { MyInterface, MyClass, MyInheritedClass } from "foo";
let x: MyInterface = { MyProperty: "hello!!" };
let y: MyClass = new MyClass();
let z: MyInheritedClass = new MyInheritedClass();

Resources