anon
anon

Reputation:

Why are my getter/setter not compiling in TypeScript?

I have a class with the following getter/setter defined:

class ConfigStoreController {
    get debugMode() {
        return (async () => await this.GetConfigParameter("debugMode"))();
        }

    set debugMode(value: string) {
        (async () => await this.SetConfigParameter("debugMode", value))();
    }

    private async GetConfigParameter(parameter: string) {
        return await RX.Storage.getItem(parameter);
    }

    private async SetConfigParameter(param: string, value: string) {
        return await RX.Storage.setItem(param, value);
    }
}

export default new ConfigStoreController();

The getter is marked as incorrect because of the setter, that is, if the latter is removed, then the getter is OK.

The error is the following:

return (async () => await this.GetConfigParameter("debugMode"))(); error TS2322: Type 'Promise' is not assignable to type 'string'.

To be clear, the getter alone compiles fine:

get debugMode() {
    return (async () => await this.GetConfigParameter("debugMode"))();
}

What is wrong with my code?

Upvotes: 2

Views: 2597

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

Since your getter contains an async operation there is no way to have it directly retrun string. It does not matter if you wrap the async operation in an anonymous function, that function call will return a Promise<string>. This means the type of the property will be Promise<string>

The getter alone works, because the property type would be Promise<string> which is not a problem. It stops working if you also have a setter and the parameter of the setter does not have the same type as the return of the get.

You can create property that is a Promise<string> instead.

class ConfigStoreController {
  GetConfigParameter(p: string): Promise<string> {
    return Promise.resolve(p)
  }
  SetConfigParameter(p: string, value: string): Promise<void> {
    return Promise.resolve(void 0)
  }
  get debugMode() {
    return this.GetConfigParameter("debugMode");
  }

  set debugMode(value: Promise<string>) {
    // There is no way to wait for this operation to finish from the outside, this might be an issue
    // Also unhandled errors from the anonymous method are not handled and are not propagated to the caller, since the set is async
    (async () => this.SetConfigParameter("debugMode", await value))(); 
  }
}

A better solution is probably to leave the getter and have a set method instead:

class ConfigStoreController {
  GetConfigParameter(p: string): Promise<string> {
    return Promise.resolve(p)
  }
  SetConfigParameter(p: string, value: string): Promise<void> {
    return Promise.resolve(void 0)
  }
  get debugMode() {
    return this.GetConfigParameter("debugMode");
  }

  async setDebugMode(value: string) {
      this.SetConfigParameter("debugMode", await value)
  }
}

Upvotes: 3

Related Questions