Search code examples
javascriptangulartypescriptmodeliife

Export and use a IIFE class in TypeScript


I'm trying to do a model class with privacy, so I have this class with clousures in Answer model file:

export class Answer {
  getId;
  getText;

  constructor(id: string, text: string) {
    const idPrivate = id;
    const textPrivate = text;

    this.getId = () => idPrivate;
    this.getText = () => textPrivate;
  }
}

So I can use it in this way in other files:

import {Answer} from '../shared/model/Answer';
...
const answers: Array<Answer> = [];
answers.push(new Answer('1', '1'));

Now, with ES6 we have Symbol, so I'm trying to do the same, but I have problems to export and use the function. This is the code:

const Answer = (() => {
  const idPrivate = Symbol();
  const textPrivate = Symbol();

  class Answer {
    constructor(id: string, text: string) {
      this[idPrivate] = id;
      this[textPrivate] = text;
    }

    getId() {
      return this[idPrivate];
    }

    getText() {
      return this[textPrivate];
    }
  }

  return Answer;
})();

export {Answer};

How can I use this IIFE function? For example for this code:

const answer = Answer('ss', 'ss');

I get this error message: "Method expression is not of Function type". How can I call the Answer constructor?


Solution

  • I believe we call classes with 'new', like : new Answer()