打字稿类型“未定义”不能分配给类型“ T”

时间:2019-12-16 19:39:24

标签: typescript

enter image description here在ci管道上编译时,我在控制台上收到错误Type 'undefined' is not assignable to type 'T'和“ return void 0”错误。 谁能告诉我代码中有什么问题以及如何解决这些错误

export function wait(ms: number): Promise<void> {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

export async function mapAsync<TIn, TOut>(
  items: TIn[],
  mapper: (item: TIn, index?: number) => Promise<TOut>,
): Promise<TOut[]> {
  const results: TOut[] = []

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    const result = await mapper(item, i)
    results.push(result)
  }

  return results
}

export async function findAsync<T>(items: T[], predicate: (item: T, index?: number) => Promise<boolean>): Promise<T> {
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    const matches = await predicate(item, i)

    if (matches) {
      return item
    }
  }

  return void 0
}

谢谢

1 个答案:

答案 0 :(得分:1)

返回语句return void 0应该是一个与预期返回类型Promise<T>匹配的承诺。即使您没有运行该功能。 TS编译器将生成错误。

export function findAsync<T>(items: T[], predicate: (item: T, index?: number) => Promise<boolean>): Promise<T> {
  return new Promise<T>(async (resolve) => {
      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        const matches = await predicate(item, i)

        if (matches) {
          resolve(item)
        }
      }

      resolve(0)
  });
}