TypeScript - What does importing and exporting interfaces as type do?
Asked Answered
H

1

8

The TS docs mention interfaces and type aliases, but I can't seem to find much info on importing or exporting interfaces as type and was hoping to get some clarification:

For example an interface can be exported as:

// located in ./MyInterface.ts
export interface MyInterface
{
    foo: string;
    bar: () => number;
}

export type {MyInterface as MyInterfaceType}

and it can be imported as:
import {MyInterface} from "./MyInterface"
or
import type {MyInterface} from "./MyInterface"
or
import {MyInterfaceType} from "./MyInterface"
or
import type {MyInterfaceType} from "./MyInterface"

Can anyone explain the difference in behavior between each interface import?

Hymnology answered 20/5, 2021 at 2:10 Comment(0)
H
9

TypeScript 3.8 adds a new syntax for type-only imports and exports

export type { MyInterface as MyInterfaceType }

Only export MyInterface type with alias MyInterfaceType.

export type only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.

And

export interface MyInterface
{
    foo: string;
    bar: () => number;
}

It's a ECMAScript 2015 module named export.

Starting with ECMAScript 2015, JavaScript has a concept of modules. TypeScript shares this concept.

Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.

See Exporting a declaration

Heaves answered 20/5, 2021 at 6:13 Comment(1)
First off, thank you sooooo much for that link to the "type-only imports and exports". I never would of found that myself! But don't interfaces get erased from TypeScript output too? I thought Interfaces were essentially types that can be extended by other interfaces and/or implemented by classes. While literal types are like interfaces, except they can't be extended (but can be combined via unions) and bound to objects OR primitives?Hymnology

© 2022 - 2024 — McMap. All rights reserved.