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
'.