How to define global function in TypeScript?

前端 未结 3 1033
心在旅途
心在旅途 2020-12-06 16:22

I want to define a global function that is available everywhere, without the need to import the module when used.

This function aims to replace the safe navigation o

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 16:45

    You're defining the type for the compiler, but not actually attaching it to the global namespace — window in the browser, global in node. Instead of exporting it from the module, attach it. For isomorphic use, use something like...

    function s() { ... }
    
    // must cast as any to set property on window
    const _global = (window /* browser */ || global /* node */) as any
    _global.s = s
    

    You can also ditch the .d.ts file and declare the type in the same file using declare global, e.g.

    // we must force tsc to interpret this file as a module, resolves
    // "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."
    // error
    export {}
    
    declare global {
      function s(someObject: T | null | undefined, defaultValue?: T | null | undefined) : T;
    }
    
    const _global = (window /* browser */ || global /* node */) as any
    _global.s = function(object: T | null | undefined, defaultValue: T | null = null) : T {
      if (typeof object === 'undefined' || object === null)
        return defaultValue as T;
      else
        return object;
    }
    

提交回复
热议问题