Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global function in TypeScript?

Tags:

typescript

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 operator (?) available in C#. For the sake of readability, I don't want to prefix the function with a module name.

Global.d.ts:

declare function s<T>(someObject: T | null | undefined, defaultValue?: T | null | undefined) : T; 

Global.tsx:

///<reference path="Global.d.ts" />  export function s<T>(object: T | null | undefined, defaultValue: T | null = null = {} as T) : T {     if (typeof object === 'undefined' || object === null)         return defaultValue as T;     else         return object; } 

App.tsx (root TypeScript file):

import 'Global'; 

Other TSX file (method usage):

s(s(nullableVar).member).member; //Runtime error 

This compiles fine, however, in the browser this throws 's is not a function'.

like image 726
olivierr91 Avatar asked Dec 10 '17 06:12

olivierr91


People also ask

How do you write a global function in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.

How do I create a global array in TypeScript?

If you create the array inside the function then it is only accessible from within the function body. You can declare it outside of the function: let ArrayRoute = []; function route(permutation, origins) { var myroute = origins[0]; ArrayRoute.


1 Answers

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; } 
like image 176
caseyWebb Avatar answered Sep 22 '22 17:09

caseyWebb