Private functions in Typescript

3k Views Asked by At

Note that I have already checked out this question, but the answers to it do not seem to be correct.

If I wanted to have private methods in regular JavaScript (which the answers suggest is not possible), I'd do something like this:

function myThing() {
    var thingConstructor = function(someParam) {
        this.publicFn(foo) {
           return privateFn(foo);
        }
        function privateFn(foo) {
           return 'called private fn with ' + foo;
        }
    }
}

var theThing = new myThing('param');
var result = theThing.publicFn('Hi');//should be 'called private fn with Hi'
result = theThing.privateFn; //should error

I'm trying to figure out what the syntax is to encapsulate the private function in TypeScript. If it turns out you can't, that's fine, but given that the answers in that older question incorrectly state that you can't create private methods in ordinary JavaScript, I am unwilling to just take those answers as authoritative.

1

There are 1 best solutions below

0
On

So, it turns out it's just as simple as marking the method private. The thing I was missing is to be able to use the method is you need to use the this keyword.

So

export class myThing {
   constructor(){}
   publicFn(foo) {
        return this.privateFn(foo);
   }
   private privateFn(foo) {
        return 'called private fn with ' + foo;
   }
}