1
votes

I am trying to understand the behavior of declaration merging. I have created a declaration file that redeclares one function interface of the module. The npm module 'schemavalidator' comes with its own typings.

I am using this module only as an example to demonstrate the behavoir. The question has noting to do with schemavalidator module.

What I have noticed is even if I do not import my declaration file the typescript still uses it.

What I'm trying to do is to use my custom declaration file only when I import it with the import statement.

Here are my 2 files

First my custom declaration file. Here I first re-export everything from npm module jsonschema. Second I redefine just one function interface.

enter image description here

And here is my file that uses this redefined CustomFormat interface. Notice I am not importing mytypes file anywhere. enter image description here

Notice the IDE is already complaining about wrong type. And where running tsc command I am getting error from typescript compiler enter image description here

So it clear to me that my custom declaration declared in mytypes.ts are processed by typescript even when the file mytypes.ts is not imported anywhere in my program.

This is not what I am trying to achieve. I want the definition to be redefined only if mytypes is imported with import statement in schemavalidator file and in all other files it should use the definition that come with npm module.

Is it possible? import '../mytypes'

1

1 Answers

0
votes

Declaration file can contain the keyword declare and that means it is globally declared. In the whole project that module is accessible.

Replace this:

declare module

with this:

export module

Declaring is used in a non-module project, for example in a browser (Babel compiler) or some other implementation of JS with TS.

I can't say using declare is bad or good practice. People also use this:

export declare module "myModule" {
  export const constant = "I am global and I can be part of import";
}

Try to understand what to use:

Example: creating online coding playground with own libs.

Solution: declare

Example: open-source project for many platforms.

Solution: export declare

Example: creating TypeScript React app for personal or production use

Solution: export

See TypeScript Documentation for more.