Reference TypeScript dom lib types locally

1.8k views Asked by At

Several types from TypeScript built-in DOM lib needs to be used in local module for cross-platform code piece, e.g.:

// foo.ts
export let foo: EventListener = (e) => ...;

This can be achieved by adding:

/// <reference lib="dom" />

The problem is that other modules in this project become polluted with DOM-related types, while they aren't specific to browser or DOM.

// bar.ts
class Animation {
    ...
}

This results in name collision errors for any variables that may have the same names as browser globals, e.g.:

Duplicate identifier '...'.ts(2300)

lib.dom.d.ts: '...' was also declared here.

Definitions of the following identifiers conflict with those in another file: ... ts(6200)

lib.dom.d.ts: Conflicts are in this file.

Cannot redeclare block-scoped variable '...'.ts(2451)

lib.dom.d.ts: '...' was also declared here.

I would prefer to avoid pasting a hierarchy of types like EventListener from lib.dom.d.ts if possible.

How can types from built-in libs be used in one local module without affecting other modules?

1

There are 1 answers

0
francis duvivier On

As answered here on stack overflow and on TypeScript's GitHub, this is not possible within a single TypeScript project and this is by design.

But so as a workaround, you can make separate TypeScript projects for the modules that should have access to dom types and for the modules that don't.