Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling local types name collision with global native types

Tags:

typescript

Say I want to define types / interfaces like Node, ChildNode. Both of these are in the global DOM types. If I define them or import them, my local types will override the native types - as intended. But what if I want to use the native type in a file that uses my custom type? Is it possible to add some namespace or import the native type with a different name so they can coexist?

like image 351
Maciej Krawczyk Avatar asked Nov 02 '25 07:11

Maciej Krawczyk


1 Answers

An alias to a native type can be created by declaring it in the global namespace.

global.ts (a file present in the path oftypeRoots of tsconfig.json)

declare global {
  type DOMNode = Node;
  type DOMChildNode = ChildNode;
}

This makes DOMNode and DOMChildNode globally available as aliases of Node and ChildNode respectively. That means I can define my own type ChildNode and be able to use the DOM type in the same file with DOMChildNode.

type ChildNode = { /* ... */ }

let myNode: ChildNode;
let domNode: DOMChildNode;

This can also be implemented with a local import

export type DOMNode = Node;
export type DOMChildNode = ChildNode;
import type { DOMNode } from './types';
like image 59
Maciej Krawczyk Avatar answered Nov 05 '25 14:11

Maciej Krawczyk



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!