typescriptclassexportstack-size

RangeError: Maximum call stack size exceeded - Typescript


When I try to get the name of the Player class in index.ts I get the following error:

/Users/pp/Developer/Typescript/src/lib/player.ts:10
    public get name() { return this.name; }
                                    ^
RangeError: Maximum call stack size exceeded
    at Player.get name [as name]

Here is the code: lib/player.ts:

export class Player {
    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    public get name() { return this.name; }
    public set name(value: string) { this.name = value; }
}

index.ts:

import { Player } from './lib/player';

const player = new Player('name');
console.log(player.name);

Solution

  • Accessing this.name calls get name() which accesses this.name which calls get name() and so on ad infinitum (or, until you exhaust the call stack).

    You probably intended to do:

    export class Player {
        private _name: string;
        
        constructor(name: string) {
            this._name = name;
        }
        
        public get name() { return this._name; }
        public set name(value: string) { this._name = value; }
    }