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
global.ts(x) needs just a little tweak to be a valid "global module" (a module with side effects only): remove the export keyword and add some code to augment the global object. You can also provide the global declaration in the same file and remove global.d.ts.
function _s(object: T | null, defaultValue: T = {} as T) : T {
return object == null
? defaultValue
: object as T;
}
// Global declaration
declare var s: typeof _s;
// Global scope augmentation
var window = window || null;
const _global = (window || global) as any;
_global.s = _s;
To use it, just import the module once, for instance in App.tsx via a global import: import './global';.
Tested with mocha, chai, ts-node:
import { expect } from 'chai';
import './global'; // To do once at app bootstrapping
describe('global s()', () => {
it('should replace null with empty object', () => {
const result = s(null);
expect(result).to.eql({});
});
it('should replace undefined with empty object', () => {
const result = s(undefined);
expect(result).to.eql({});
});
it('should replace null with the given default value', () => {
const defVal = { def: 'val' };
const result = s(null, defVal);
expect(result).to.eql({ def: 'val' });
});
it('should preserve defined object', () => {
const object = { bar: 'a' };
const result = s(object);
expect(result).to.eql(object);
});
});