Search code examples
typescriptprototypedeclaration

TypeScript declare merge for core types


How can I do typescript declare merge for built in types with import.

Actually I am trying to do interface declare merge per instruction in this document: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

  1. When I do a merge without any import, it works:
interface Function {
  applyParams?(aa: string[]): string
}

function f() {}

const a:  Function  = f

a.applyParams && a.applyParams(["1", "2"]);
  1. However if I add an import statement to beginning of file, I am getting error, like on example bellow:
import { MyType } from "./MyType";

interface Function {
  applyParams?(aa: string[]): MyType;
}

function f() {}

const a: Function = f;

a.applyParams && a.applyParams(["1", "2"]);

The error is: TS2559: Type '() => void' has no properties in common with type 'Function'.


Solution

  • It works if you wrap your definition in global block.

    import { MyType } from "./MyType";
    
    declare global {
      interface Function {
        applyParams?(aa: string[]): MyType;
      }
    }
    
    function f() {}
    
    const a: Function = f;
    
    a.applyParams && a.applyParams(["1", "2"]);
    

    This is probably because TypeScript processes files with and without import statements differently. Files with imports are considered as modules and have local scopes, while others can be considered as declaration files and have global scope by default.