Question: Typescript allows readonly class members to be initialized in the constructor, but what if data comes as a response to asynchronous request?

```
class Test { 
  readonly data;
  constructor() {
    setTimeout(() => {
        this.data = 15 // error
    });
  }
}

```

Answer: 
As far as I know, typescript only allows you to set a readonly class property in the constructor function. Since you're setting it as part of a callback function (even though the callback is in the constructor), typescript is going to produce an error.

The way around this is to do one of two things. For a quick and easy fix, explicitly override that when you need to set it, possibly by casting `this` to be `any`, or by adding a `// @ts-ignore` comment above that line. So for your example:

```
class Test { 
  readonly data;
  constructor() {
    setTimeout(() => {
        (this as any).data = 15 // No error, manually overridden

        // OR:

        // @ts-ignore
        this.data = 15  
    });
  }
}

```

Otherwise, you can use getters and setters to allow you to freely set the property from within the class, but to all consumers of the class, it will appear as readonly:

```
class Test { 
  private _data;
  constructor() {
    setTimeout(() => {
        this._data = 15 // No error
    });
    }

    get data() {
        return this._data;
    }

}

const test = new Test();

let d = test.data;
test.data = "foo"; // Cannot assign to 'data' because it is constant or readonly

```
I have same problem and I'm using another work-around. I pass the Promise to the property.

```
class Test { 
  readonly dataPromise: Promise<number>;
  constructor() {
    this.dataPromise = new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(15)
      }, 1000);
    })
  }
}

```

Also optionally, we can also wrap it with a getter, (although it's still async) like this: ([origin](https://medium.com/trabe/async-getters-and-setters-is-it-possible-c18759b6f7e4))

```
class Test { 
  readonly dataPromise: Promise<number>;
  constructor() {
    this.dataPromise = new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(15)
      }, 1000);
    })
  }
  // new below
  get data() {
    return ( async () => await this.dataPromise )()
  }
}

```

After writing this, I saw @Aaron Beall already suggested this 4 years ago...