.

Usually when we define ts type declarations, using the DECLARE keyword in the.d.ts file works fine. This would suffice for global constants or some simple type definition. However, more complex use conditions are not excluded, such as the use of a module declared by other modules. If other modules are introduced in a.d.ts file using import or require, then TS will treat it as a module, and all type declarations in the file will be directly invalidated.

How to solve

First define global.ts as follows:

export interface GlobalState {
  loading: boolean;
  pageNum: number;
  pageSize: number;
}
Copy the code

If you want to use GlobalState in typings.d.ts, you need to import global.ts. Importing it directly at the top of typings.d.ts will invalidate all global declarations.

// typings.d.ts

import { GlobalState } from 'global.ts';

declare interface Window {
  _store: {
    _state: any; _dispatch: any; }}Copy the code

An error is thrown where window._store is used._store does not exist on type window.

TypeScript ECMAScript 2015As with any containing top-levelimportorexportFiles are treated as a module. Conversely, if a file does not have a top-levelimportorexportDeclaration, so its contents are treated as globally visible (and therefore visible to the module), which is why there is sometimes no reference to a.d.tsFile, but in the.d.tsType definitions inside files can still be detected in other files because of the.d.tsThe type defined by the file has become global

Mount the type declarations you want to use to the global namespace by creating it.

// Create a global.d.ts file to declare the global namespace
import { GlobalState, GlobalDispatch } from 'global.ts';

declare namespace GlobalType {
  interface G_State extends GlobalState {}
  interface G_Dispatch extends GlobalDispatch {}
}

export = GlobalType;
export as namespace GlobalType;
Copy the code

Then use GlobalType.globalState in the file where you want to use the GlobalState type declaration.

// typings.d.ts
declare interface Window {
  _store: {
    _state: GlobalType.G_State ; _dispatch: GlobalType.G_Dispatch ; }}Copy the code

Pay attention to

Note that if the global namespace is duplicated, the duplicate namespace will be overwritten and no error will be reported. Therefore, be careful not to duplicate the global namespace.

What does the export = statement in TypeScript’s D.ts declaration file do?

TypeScript can generate TS code from the CommonJs and AMD specifications, and since the two are incompatible, the export = syntax is used to unify the two so that TS can support them.

What does the export as Namespace statement in TypeScript’s D.ts declaration file do?

Export as namespace Indicates to mount a namespace to the global namespace so that it can be used as a global variable

The project practice

The type definition

Example Mount a global namespace

The specific use

Ts correctly deduces type declarations