Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 {type MyInterfaceType} from "./MyInterface"
or
import {MyInterfaceType} from "./MyInterface"

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

like image 568
Snap Avatar asked Mar 13 '26 10:03

Snap


1 Answers

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

like image 191
slideshowp2 Avatar answered Mar 16 '26 02:03

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!