Using a type alias to create a new name for a preexisting type like Document

I often need to work with auto-generated types that have been generated by Swagger based on an API definition.

These types sometimes clash with the names of preexisting types. For example the Document object, which normally refers to: Any web page loaded in the browser and serves as an entry point into the web page’s content, but in my case is also the name of an interface generated by Swagger.

Since you don’t need to import the Document type to use it in TypeScript / Angular projects, every time I try to use the generated Document class it’s referring to the DOM’s Document by default.

This can be fixed by adding an import statement, but to avoid dealing with this project-wide we can use type aliases which let us give a type a new name:

type MyAppDocument = Document;

Since I can’t change the generated Document file itself, it would get overwritten the next time it’s generated, I create a type-alias.ts file like this:

import { Document } from './document';

export type MyAppDocument = Document;

Which then allows me to use the new MyAppDocument type everywhere.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s