1

I am trying to write private attributes in a Typescript class but they are fully accessible and can be overwritten by my jest tests. Am I doing something wrong or is this normal?

This question received an answer related to using # instead of private, but isn't this pure javascript? Shouldn't Typescript's private keyword prevent me from overwriting or even accessing this value?

My class:

export class TodoItemID {
  public constructor() {
    return "TodoItem#" + Math.random() * 100000000000000000;
  }
}

class TodoItem {
  private id: TodoItemID = new TodoItemID();
  private name: Required<String>;
  private description: String;
  private completed: boolean;
  private todoListId: TodoListID;

  constructor(name: Required<String>) {
    this.name = name;
  }
}

export default TodoItem;

My test (note: both tests pass):

import TodoItem, { TodoItemID } from "./";

describe("TodoItem", () => {
  let todoItem;
  const todoItemName = "Todo Item for testing purposes";
  beforeEach(() => {
    todoItem = new TodoItem(todoItemName);
  });

  it("should have an id", () => {
    expect(todoItem.id).toBeInstanceOf(TodoItemID);
    todoItem.id = "blabla";
    expect(todoItem.id).toBe("blabla");
  });
});

Check out the snapshot here.

  • 2
    This is *normal*. TypeScript does not change the runtime behavior of your code. Thus, when your code is compiled and `private` is stripped, it's basically a public property. – kelsny Oct 29 '22 at 03:19
  • Your TypeScript code has [quite a few compiler errors](https://tsplay.dev/mL2jKw) so I wouldn't be surprised if runtime behavior does things you don't expect. If I clear up all the *unrelated* errors, you have the source of your issue: [you are illegally accessing private members](https://tsplay.dev/w17Xlm). The compiler warns you about this and it's up to you to resolve those errors (by not accessing them from outside the class). – jcalz Oct 29 '22 at 03:25
  • See the linked questions/answers for more information – jcalz Oct 29 '22 at 03:28

0 Answers0