简体   繁体   中英

TS2345: Argument of type 'Promise<ReadonlyArray<Object>>' is not assignable to parameter of type 'T | PromiseLike<T> | undefined'

What I am trying to do is return the the ReadonlyArray<> in my promise so I can return it back to the original method that called 'dispatchToThisProcess', the reason why I am doing is to abstract the state update so I can change it to update multiple processes in the future. Bellow is my code:

private dispatchToThisProcess<T extends object>(action: Action): Promise<T> {
    return this.updateState(action.name, action)
  }
  // to be called by the dispatchToThisProcess
  private updateState<T extends object> (name: string, args: any): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      console.log('In updateState, this replaced the send<T>(...) method')
      switch (name) {
        case 'add-repositories': {
          const addedRepos: ReadonlyArray<Repository> = new Array<Repository>()
          for (const path of args) {
            const addedRepo: any = Promise
            .resolve(this.repositoriesStore.addRepository(path))
            .then(result => addedRepo)
            addedRepos.join(addedRepo)
          }
          const returned = Promise.resolve(addedRepos)
          resolve(returned)
          break;
        }
        default: {
          reject()
          break;
        }
      }
    })
  }

Here is the error I get:

 error TS2345: Argument of type 'Promise<ReadonlyArray<Repository>>' is not assignable to parameter of type 'T | PromiseLike<T> | undefined'.
  Type 'Promise<ReadonlyArray<Repository>>' is not assignable to type 'PromiseLike<T>'.
    Types of property 'then' are incompatible.
      Type '<TResult1 = ReadonlyArray<Repository>, TResult2 = never>(onfulfilled?: ((value: ReadonlyArray<Rep...' is not assignable to type '<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) |...'.
        Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
          Types of parameters 'value' and 'value' are incompatible.
            Type 'ReadonlyArray<Repository>' is not assignable to type 'T'.

I looked it up, people say to add that T extends object but that did not help in my case, I do not really know where to go from here. I'm using TypeScript 2.4.0.

updateState is only returning a single T. You probably want it to return a ReadonlyArray of them.

  private updateState<T extends object> (name: string, args: any): Promise<ReadonlyArray<T>> {
    return new Promise<ReadonlyArray<T>>((resolve, reject) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM