Skip to content

Rule suggestion: Prefer "import type" #1786

Closed
@ghost

Description

Mostly separating this out from #1436 so it can have a dedicated issue.

TypeScript 3.8 adds an import type syntax which allows you to import type definitions only, for ease of transpilation via tools which don't have type checking like babel. For transpilers, these definitions are ignored and removed on transpilation.

The newer compiler also has an importsNotUsedAsValues compiler option to clarify whether you want to enforce the use of import type syntax, with the three options:

  1. remove: Don't transpile import type definitions, not loading any stateful changes (default)
  2. preserve: Transpile import type definitions, loading any stateful changes
  3. error: Error when plain imports are for types only, requiring a separation of stateful/value imports and type imports

That latter option looks like a good candidate for a rule in typescript-eslint. Although the compiler will warn on these errors, an eslint rule can also have an applicable fix as well. This is also not a possible rule for eslint-plugin-import, as it requires type checking.

This rule, when enabled, will match the behaviour of the error variant of the importsNotUsedAsValues flag, providing an applicable fix.

Example code:

import { Type, Class, CONST } from 'module';

function doThing(value: Type): void {
    if (value instanceof Class) {
        doAnotherThing(value);
    } else if (value === CONST) {
        doDifferentThing(value)
    } else {
        doUsualThing(value);
    }
}

Suggested fix:

-import { Type, Class, CONST } from 'module';
+import type { Type } from 'module';
+import { Class, CONST } from 'module';

Metadata

Metadata

Assignees

No one assigned

    Labels

    awaiting responseIssues waiting for a reply from the OP or another partypackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy