Reuse a type

INPUT · Slides

Share types between files

01 / 06

Types can go out of the file too

Remember splitting files up by job in the JavaScript course and joining them with export and import? Those two work on types just the same.

The more types you write, the more you end up using the same one over and over. You want the type for a person in the file that makes the data and in the file that shows it. So write it in one place and let everybody fetch it.

02 / 06

Send it out with export type

Sending it out works just like with values. Put export in front of type and you are done.

The file below holds nothing but one type. Making a file whose job is to hold types is a common shape in real apps too.

// person.tsexport type Person = {  name: string;  age: number;};

03 / 06

Take it in with import type

On the receiving side you put type after import. That makes it clear — to the reader and to TypeScript — that this line brings in a type only.

After that you use the Person you brought in exactly like a type written in your own file.

// main.tsimport type { Person } from "./person.js";const yui: Person = {  name: "Yui",  age: 20,};console.log(yui);

Result

{ name: "Yui", age: 20 }

04 / 06

What you brought in as a type cannot be used as a value

import type brings in types only, so it stops you if you try to use it as a value. Below, the value tama was brought in with import type by mistake.

It says exactly what happened, and the fix is just as plain. When you want the value, import it without the type.

// main.tsimport type { tama } from "./cat.js";console.log(tama.name);

Result

Type error: 'tama' cannot be used as a value because it was imported using 'import type'.

05 / 06

The import type line disappears

In chapter 1 we said types disappear before anything runs. The import type line is the same: nothing of it is left after the conversion.

It is a line that only fetches a type, so it is not needed when the code runs. That is why writing import type also tells the reader "this line has nothing to do with what happens".

// what you wroteimport type { Person } from "./person.js";const yui: Person = { name: "Yui" };console.log(yui.name);// after the conversionconst yui = { name: "Yui" };console.log(yui.name);

06 / 06

Bring a type and a value in together

When you want both a type and a value from the same file, splitting it over two lines is the clearest. One is import type, the other your everyday import.

The reader can tell at a glance from the line which one runs. Right then, let us pass some types about.

// main.tsimport type { Cat } from "./cat.js";import { tama } from "./cat.js";const cat: Cat = tama;console.log(cat.name);

Result

Tama