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?
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With