Is there a point to doing 'import type' rather than 'import' for Interfaces?

Viewed 399

Let's say that I have a class in another file that I would like to import to use its types

import type { Component } from "react";

The makes sense since Component is a class.

What if I'm importing an interface, is the import type still required? or is Typescript aware that interfaces have no value and so the type is not required.

import type { IHttpResponse } from "../lib/http";

The compiler does not complain if type is added and this kind of usage was not described in the docs

1 Answers

This depends on the value of the importsNotUsedAsValues compiler option (in tsconfig.json, or passed in from the command line).

If it set to remove (the default value), there is no difference between import and import type when you are importing an interface (or a class that is used only in type positions). In both cases, there will be no import or require statement in the compiled JavaScript (and so any side effects in the module being imported will not be executed).

If this option is set to preserve, import will cause an import statement to be emitted by the compiler even if the type being imported is an interface; import type will not.

If this option is set to error, interfaces must be imported with import type; using import will result in a compile error.

Related