TS2345:类型'Promise <readonlyarray <object>&gt;'的参数不能分配给'T |类型的参数PromiseLike <t> |未定义”

时间:2017-08-14 19:48:06

标签: typescript

我要做的是返回ReadonlyArray&lt;&gt;在我的承诺中,我可以将其返回到称为“dispatchToThisProcess”的原始方法,我之所以做的是抽象状态更新,所以我可以将其更改为将来更新多个进程。贝娄是我的代码:

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;
        }
      }
    })
  }

这是我得到的错误:

 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'.

我查了一下,人们说添加T扩展对象,但这对我的情况没有帮助,我真的不知道从哪里开始。我正在使用TypeScript 2.4.0。

1 个答案:

答案 0 :(得分:0)

updateState只返回一个T.你可能希望它返回它们的ReadonlyArray。

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