import-js / eslint-plugin-import

ESLint plugin with rules that help validate proper imports.
MIT License
5.57k stars 1.57k forks source link

No errors for TypeScript `import` types #1675

Open OliverJAsh opened 4 years ago

OliverJAsh commented 4 years ago

Docs on import types: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#import-types

Reduced test case (all dependencies are latest):

// ./cypress/test.ts

// Expected error, got one
// Unexpected path "../app/helpers/api" imported in restricted zone
import Api from '../app/helpers/api';

// Expected error, but got none
type Api = typeof import('../app/helpers/api');
// .eslintrc.js
const config = {
  extends: ['plugin:import/typescript'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
  },
  plugins: ['import'],
  rules: {
    'import/no-restricted-paths': [
      2,
      {
        basePath: '.',
        zones: [
          {
            target: './cypress',
            from: './app',
          },
        ],
      },
    ],
  },
}

module.exports = config;
ljharb commented 4 years ago

This isn't a TypeScript thing, import() is a language feature, dynamic import. That it's in type-space is unrelated.

Dynamic imports aren't usually checked, because they aren't forced to be static, and it's impossible to reliably statically know the import path.

OliverJAsh commented 4 years ago

Good point.

Dynamic imports aren't usually checked, because they aren't forced to be static, and it's impossible to reliably statically know the import path.

When using them at the type-level, they are required to be static, so it does makes sense to lint them in this context.

ljharb commented 4 years ago

At that point tho, doesn't typescript itself warn on it?

OliverJAsh commented 4 years ago

Why would TS warn about this?

type Api = typeof import('../app/helpers/api');

The module path is valid. It's just we want to disallow it, via no-restricted-paths.

ljharb commented 4 years ago

ahhh gotcha, thanks for clarifying.

Baumgaer commented 4 years ago

I am feeling free to ask for an additional parameter for each zone.

Is it possible to allow typescript special imports for types?

import type {MyType} from "/normally/forbidden/import/in/restricted/area"

It would be nice to disallow imports which stay in compiled javascript but allow imports of type in this way. The parameter for the zone could be named as "allowTypeImports": true

fregante commented 2 years ago

None of these run any code so they should be allowed:

import "/normally/forbidden/import/in/restricted/area" // if the file is d.ts, but rare
import {MyType} from "/normally/forbidden/import/in/restricted/area"
import {type MyType} from "/normally/forbidden/import/in/restricted/area"
import type {MyType} from "/normally/forbidden/import/in/restricted/area"
type MyType = typeof import("/normally/forbidden/import/in/restricted/area");