Search code examples
typescriptextend

How to extend global named functions in Typescript


I've define a global named function such as:

function foo() { 
  foo._cache = {}; 
}

How do I extend a property to foo like _cache.

It seems the code below has no effact.

interface foo {
    _cache: any;
}

Solution

  • How do I extend a property to foo like _cache.

    The function foo is not associated with the interface foo as they are in completely different declaration spaces (more on those).

    If you want foo to be a function that also has a cache property you have to do it in two steps e.g:

    const foo: {
        (): void;
        _cache: any;
    } = function () {
    } as any;
    foo._cache = {};