Start learning free

LESSON 632 OF 675 · OBJECT-ORIENTED PROGRAMMING

Private Fields in TypeScript

Lesson

TL ; DR:

  • TypeScript has the private keyword: only code inside the class can use that field.

    class Dog {
        private name: string;
    
        constructor(name: string) {
            this.name = name;
        }
    
        getName(): string {
            return this.name;
        }
    }
    

  • Outside the class, rex.name is a compile error. The check exists only at compile time: the compiled JavaScript has no private.

  • JavaScript's own #name fields (ES2022) are truly private at run time, and TypeScript supports them too.



Full lesson:

For decades, JavaScript classes had no real privacy — programmers used a leading underscore (_name) as a convention. TypeScript adds the private keyword, and ES2022 added true private fields with the # prefix.


How private works

  • You declare the field at the top of the class body with its type: private name: string;
  • You access it as this.name inside the class's methods.
  • Trying to access it from outside is a compile error (the compiler reports it), not a run-time error.

Your task

The Dog class declares private name and the constructor stores into it. Add a getName() method, with a string return type, that returns this.name.

Dog's name: Rex
STEP 1 OF 2
    Ctrl + Enter to check