How to export a Type in TypeScript
We can use a named and default export to export a type in TypeScript.
export type Some = { ... }
type More = { ... }
export default More
We import types like this:
import DefaultType, {Some} from './types-file.ts'
Named Export
Here is an example of exporting a type. We can export type on the same line it was declared:
// types-1.ts
// π named export
export type Some = {
one: string
two: number
}
We can export type after it has been declared:
// types-2.ts
type Other = {
three: string
four: number
}
// π named export
export { Other }
Here is how we would import the types:
// using-type-1.ts
// π named import
import { Some } from "./types-1"
import { Other } from "./types-2"
const some: Some = {
one: "string",
two: 2
}
const other: Other = {
three: "string",
four: 4
}
Make sure that all paths are right. The example above assumes that all files are located in the same directory.
Default Export
TypeScript uses modules, in the same way that JavaScript does.
You can only import a type from a different file, if it has been exporting using named or default export.
You can have as many named exports as you want per file, but only one default export per file.
If you try to use multiple default exports in a file, you will get an error.
// types-3.ts
type Some = {
one: string
two: number
}
//π default export
export default Some
// types-4.ts
type Some = {
one: string
two: number
}
type More = {
one: string
two: number
}
//π default export
// βοΈ Error:
// A module cannot have multiple default exports.ts(2528)
export default Some
export default More
Using both: Default and Named export
Declaring types and exporting them as both: default and named export
// types-5.ts
type Some = {how-to-export-impot-type-in-typescript
one: string
two: number
}
type More = {
one: string
two: number
}
//π default and named export in one line
export { Some as default, More }
Importing types:
// using-type-3.ts
//π default and named import in one line
import DefaultType, { More } from "./types-5"
const some: DefaultType = {
one: "string",
two: 2
}
const other: More = {
one: "string",
two: 2
}
βNotice: we didn't wrap the default import in curly braces.