How to define global function in TypeScript?

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<T>(someObject: T | null | undefined, defaultValue?: T | null | undefined) : T;
}

const _global = (window /* browser */ || global /* node */) as any
_global.s = function<T>(object: T | null | undefined, defaultValue: T | null = null) : T {
  if (typeof object === 'undefined' || object === null)
    return defaultValue as T;
  else
    return object;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)