Merge interface from namespace in module declaration file

后端 未结 2 1744
情书的邮戳
情书的邮戳 2021-01-23 05:52

I have a javascript library which has a type definition file here: https://github.com/tyranid-org/tyranid/blob/master/tyranid.d.ts which is exposed via the typings

相关标签:
2条回答
  • 2021-01-23 06:13

    You're trying to augment the module tyranid. The general syntax is pretty straightforward: here is an example of redux-thunk augmenting redux.

    However, because tyranid exports default, module augmentation is not fully supported. export = has been fixed, as discussed in this issue.

    To augment tyranid, the best I could come up with (inspired by this comment), is to throw the Tyr namespace into the global scope:

    node_modules/tyranid/tyranid.d.ts

    import * as Express from 'express';
    import * as mongodb from 'mongodb';
    
    export default TyrStatic;
    
    declare global {
      namespace TyrStatic {
        // existing implementation of the Tyr namespace
      }
    } 
    

    ./index.d.ts

    declare namespace TyrStatic {
      interface specialInterface {
        someProp: number
      }
    }
    

    (depending on whether you need this augmentation to use external modules, you might need to wrap it in a declare global {})

    src/app.ts

    import Tyr from 'tyranid'
    let specialVariable: Tyr.specialInterface = { someProp: 4 }
    
    0 讨论(0)
  • 2021-01-23 06:34

    The following ended up working...

    in node_modules/tyranid/tyranid.d.ts:

    export = Tyr // must do "import * as Tyr from 'tyranid'" instead of default
    
    declare namespace Tyr {
      export interface Document {
        // original definition...
      }
    }
    

    in mylib/tyranid-extensions.d.ts...

    declare module "tyranid" {
      interface Document {
        addedMethod(): boolean; 
      }
    }
    

    Thanks @pelle-jacobs for the help!

    0 讨论(0)
提交回复
热议问题