Tautvydas Tautvydas - 3 months ago 22
TypeScript Question

TypeScript Class how to define not prototype class function

Just starting to use TypeScript and I can't find explanation for this issue...

Lets say I have function

function test() {
function localAccessMethod() {
console.log('I am only accessable from inside the function :)');
}

this.exposedMethod = function () {
console.log('I can access local method :P');

localAccessMethod();
}
}


And I want to convert this to typescript class... So far I did it up to here:

class test {

constructor: {}

exposedMethod() {
console.log('I can access local method :P');

localAccessMethod();
}

}


How can I define that local function in the typescript class, so it wouldn't be exposed as prototype or .this... ?

Or better question, how should I convert the source code to fit TypeScript standard. I want to have function which is available for all class methods only, but is not exposed...

Answer

You can't have something in a class which won't be exposed, even private/protected members/methods are exposed in javascript and only the compiler enforces this visibility.

You have a few options:

(1) Have the "inner" function inside the main one:

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        function localAccessMethod() {
            console.log('I am only accessable from inside the function :)');
        }

        localAccessMethod();
    }
}

(2) If this is a module then place the inner function in the top level part of the module and don't export it:

function localAccessMethod() {
    console.log('I am only accessable from inside the function :)');
}

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        localAccessMethod();
    }
}

(3) If you're not using modules then wrap this thing in a namespace and export only the class:

namespace wrapping {
    function localAccessMethod() {
        console.log('I am only accessable from inside the function :)');
    }

    export class test {
        constructor() {}

        exposedMethod() {
            console.log('I can access local method :P');

            localAccessMethod();
        }
    }
}