Disable ts errors in js project - javascript

So I have a cra app and I have set up a .eslintrc.json config with the help of eslint --init. Here's how it looks:
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:react/recommended",
"airbnb",
"prettier"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"react/jsx-filename-extension": "off"
}
}
I also have a jsconfig.json file. From what I understood, this is derived from the tsconfig.json config. Here's how mine looks:
{
"compilerOptions": {
"baseUrl": "./<path/to/src>",
"checkJs": true,
"jsx": "react"
},
"exclude": ["node_modules", "build"]
}
From what I've read, if you set checkJs to true you get some features like auto-imports and from what I've tested, this is true and I like it. But what I don't like is having ts errors in my js files and getting recommended to add ts-ignore to the top of the file or to a certain line. What I can do is set the checkJs flag to false and those will go away, but so would some features like auto-import.
Can I keep the checkJs flag to true and still disable all ts errors in my js project? Is there a eslint rule for that? From what I saw, I would need to install a bunch of ts eslint packages and alter my eslint config, but this seems a bit off. Can this be done in a somewhat elegant way?

I have worked on a monorepo project that uses TypeScript for type declaration files generation only (.d.ts files) based on JSDoc/TSDoc annotations. So, no real TypeScript code is used, only special comments.
This is the merged configuration for one of the packages:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"lib": ["ESNext", "DOM"],
"allowJs": true,
"checkJs": true,
"noEmitOnError": true,
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false,
"esModuleInterop": false,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"removeComments": false,
"types": ["node", "mocha", "chai", "webpack", "tapable", "react"],
"allowSyntheticDefaultImports": true,
"noEmit": false,
"declaration": true,
"emitDeclarationOnly": true,
"declarationDir": "./types"
}
}
We get full type checking and no errors that can't be solved by pure JavaScript (our TypeScript version is ^4.2.4).
However, keep in mind that when you work with a type checker, generally you'll be forced to write your code in a stricter way (it is a pain, but it is worth it).
If you don't want to deal with TypeScript, because it may be hard to setup and maybe it is an overkill if you won't use all of its features, you can try JSDoc (in my opinion, it should have been the standard for JavaScript type annotations, but the reality is far from that).
Also consider that it is possible that you will have to provide type annotations somehow (the only way to use TypeScript as a type-checking engine without actually writing TypeScript is by using JSDoc or TSDoc which is a variant of the former specifically designed for TypeScript).
Here is a great article (there are many more, I recommend you to learn more about JavaScript type checking) (see this that specifically writes about JSDoc + TypeScript).
In our project, we do things like this:
/** #type {Array<number>} */
const myNumbersArray = [];
myNumbersArray.push(0); // OK
myNumbersArray.push('0'); // ERROR
Or
/** #module core/modules/string-utils/split-by-words */
import {parse} from './parse.js';
/**
* #description Splits passed string by words.
* #param {string} str - Input string.
* #returns {Array<string>} Results array.
*/
function splitByWords(str) {
return parse(str).map((item) => item.content);
}
export {splitByWords};
Finally, there are many JSDoc ESLint libraries that you can use.

Related

Module '"domhandler"' has no exported member 'DomElement'. Did you mean to use 'import DomElement from "domhandler"' instead?

I trying to build a react-typescript project. ii didn't install dom utils and HTML parser libraries. but when I tried to run yarn build, the following error is coming
~~~~~~~~~~
../node_modules/#types/htmlparser2/index.d.ts:17:10 - error TS2614: Module '"domhandler"' has no exported member 'DomElement'. Did you mean to use 'import DomElement from "domhandler"' instead?
17 export { DomElement, DomHandlerOptions, DomHandler, Element, Node } from 'domhandler';
~~~~~~~~~~
../node_modules/#types/react-html-parser/index.d.ts:9:10 - error TS2305: Module '"htmlparser2"' has no exported member 'DomElement'.
9 import { DomElement } from "htmlparser2";
I tried some of follwoing steps,
added "skipLibCheck": true in tsconfig.json file
https://github.com/apostrophecms/sanitize-html/issues/333 i tried some steps whatever they said, still no use.
tsconfig.json file
{
/* https://www.typescriptlang.org/docs/handbook/react-&-webpack.html */
/* https://www.typescriptlang.org/docs/handbook/compiler-options.html */
"compilerOptions": {
"target": "es5",
"module": "commonjs" /* webpack supports imports syntax */,
"jsx": "react",
"lib": ["es5", "dom", "es2015"],
"strict": true,
"moduleResolution": "node" /* load modules like node */,
"esModuleInterop": true /* to treat commonJS 'module.exports' as 'default export' */,
"importHelpers": true,
"skipLibCheck": true,
}
}
This might be a duplicate question. But I don't know how to solve this issue, can someone help me for solving this??
If you have these errors just check your package.json.
Possibly you installed unwanted type definitions because htmlparser2 package has all necessary type definitions from the box.
If so then delete it and use #Kasunaz's answer.
I fixed this issue by configuring Typescript (editing tsconfig.json) to "Skip type checking of declaration files." (docs):
{
"compilerOptions": {
"skipLibCheck": true,
...
}
}

Import from index.ts returns undefined

I have this very simple file structure consisting of
src
index.ts
services
my-service.ts
In index.ts I have the following
export const a = 3
and in my-service.ts I do,
import { a } from '../index'
console.log(a);
this logs undefined.
When I do
setTimeout(() => console.log(a), 100);
it logs 3.
I am running the solution using
ts-node -r tsconfig-paths/register ./src/index.ts
my tsconfig looks like
{
"extends": "../../tsconfig.json",
// "include": ["src/**/*.ts"],
"compilerOptions": {
"outDir": "dist",
"allowJs": false,
"baseUrl": ".",
"rootDir": "src",
"composite": true
},
"references": [
{
"path": "../shared-tools"
}
],
"exclude": ["dist"],
"include": ["src/**/*.ts"]
}
Which extends the following root tsconfig
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
// "baseUrl": ".",
"allowJs": false,
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"types": [],
"typeRoots": [
"./node_modules/#types"
],
"paths": {
"#project/shared-tools": [
"../shared-tools/src"
]
}
}
}
That symptom suggests you have a cycle of dependencies between index.ts and my-services.ts — in addition to the dependency you've described on a in index.ts, index.ts relies on something supplied (directly or indirectly) by my-services.ts. This is called a cyclic dependency. A depends on B which depends on A.
With JavaScript's now-standard ESM static module syntax, cycles are possible but normally they can be resolved without your having to worry about them. In cases where they can't, instead of getting undefined, you get an error (if you use const as you have).
But you're telling TypeScript to rewrite your module syntax into Node's original CommonJS-inspired syntax (module.exports and require() calls). With CJS, cycles can result in your seeing undefined for things that later have a value assigned when all the module code has been run.
Ideally, the solution is to remove the cyclic dependency. If index.ts has to depend on my-services.ts, perhaps move whatever my-services.ts imports from index.ts to something else they both import from. That way, A and B both depend on C rather than on each other.
If for some reason you can't do that, you might try telling TypeScript to output JavaScript module syntax instead ("module": "ES2015" or "module": "ESNext"). Since that does static resolution (if you don't use dynamic import()), it may be able to handle the cycles for you. Node now has robust support for ESM.
Or you may not need to handle it. Even in CJS, cyclic dependencies are really only a problem if you use the dependencies in the initial module code rather than in code that runs later in response to an event (as you saw by wrapping your code using a in a setTimeout). So if the resources involved in the cycles are only needed to (for instance) respond to a network request, you may not need to worry about it at all. There's a bit more about cycles in CJS modules in Node here.

How to fix 'Typescript "Type checking in progress..." taking too long'?

Every time i run the project and change something in a file in my Vuejs front-end app which is using typescript, the typescript/webpack instantly tells compiled successfully like: DONE Compiled successfully in 635ms but the type checking will takes too long to tell there is error or not like: No type errors found Version: typescript 3.9.6 Time: 41131ms and it will use high cpu usage for this type checking which i think it is harm full for my laptop in a 8h/day developing.
I tried to set some flags in tsconfig.json as the docs says https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html:
"incremental": true,
"tsBuildInfoFile": "./buildcache/front-end",
But nothing has been changed , I also tried "watch":true , but it didn't for either. So I wonder how should we fix this problem with typescript type checking's problems( taking too long to check and high cpu usage)
Update
Here is my tsconfig:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
Update2
You can use this https://github.com/SeyyedKhandon/vuejs-persian-chat-scaffold as a reprex (clone typecheck branch), and as you can see in this simple app, it takes 2 seconds to type-check, which is not acceptable at all. Does it related to vue-composition-api plugin?
Update3
I found-out there is a flag named "skipLibCheck": true in tsconfig.json , which skips lib type checks which made type-checking 2x faster. but still its not good enough.
After spent lots of time on this problem, I decided to upgrade package.json, at the first step I've upgrade 3 packages including "#vue/composition-api": "^1.0.0-beta.3" -> "^1.0.0-beta.10" and "sass-loader": "^7.1.0" -> "^9.0.3" and "typescript": "~3.9.3", -> "~3.9.7", and suddenly the typechecking time decreases to 4s, which was very good promising.
So, here is what i did :
1.use "skipLibCheck": true flag in tsconfig.json , which skips lib type checks which will make type-checking 2x faster.
if the problem still exists -> upgrade your package.json
you can use yarn upgrade-interactive --latest but be careful about breaking changes(read the docs to fix you problems, in case of sass-loader upgrading if you have issue read https://stackoverflow.com/a/62844942/12666332)

ESLint no restricted globals with Object.values in TypeScript project

I am getting an ESLint error for no restricted globals:
const objectParamsAllNumbers = (obj: Object) =>
!Object.values(obj).find(elem => {
return isNaN(elem);
});
I tried adding ES2017.Object to my tsconfig but the error is still throwing:
{
"compilerOptions": {
"isolatedModules": true, // Warn you if you write certain code that can’t be correctly interpreted by a single-file transpilation process.
"outDir": "./dist/",
"module": "commonjs",
"target": "ES5",
"jsx": "react",
"lib": ["ESNEXT", "DOM", "DOM.Iterable", "ES5", "ES2017", "ES2017.Object"],
"allowJs": true, // Allow JavaScript files to be imported inside your project, instead of just .ts and .tsx
"checkJs": true, // When checkJs is enabled then errors are reported in JavaScript files. This is the equivalent of including // #ts-check at the top of all JavaScript files which are included in your project.
"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export
"skipLibCheck": true,
"types": ["node", "webpack-env", "#wdio/sync", "mocha", "expect-webdriverio"],
"strict": false // Enables all strict type checking options (This is too restrictive for the current code base)
},
Try accessing it on the window object like window.Object.
const objectParamsAllNumbers = (obj: Object) =>
!window.Object.values(obj).find(elem => {
return window.isNaN(elem);
});

Is there a way to export enums with ES6 settings in Typescript?

In using Typescript, I was attempting to export an enum into another file using ES6 import / export statements like so:
export enum EnumerableThing {
green,
red,
blue
}
However, when I tried to import that statement with import { EnumerableThing } from './enum' it wasn't detected and didn't affect the resulting Javascript code.
Is there a reason why this is / how to fix it?
To note, I have ES6 import statements in my tsconfig. I realize that interfaces also doesn't actually compile Javascript code, however, interfaces are exportable despite not being compiled into Javascript themselves.
Edit, here is my tsconfig file
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"jsx": "react",
"allowJs": true
},
"exclude": [
"node_modules"
],
"compileOnSave": false
}
Thanks you in advance!
If you don't actually use the import, it will not appear in the generated JS. If you refer to the value EnumerableThing, e.g. let x = EnumerableThing.green, the import will be retained.

Categories

Resources