在typescript使用泛型时候遇到promise的then方法第一个参数类型存在void情况?

在typescript中报如下错误:
错误截图

ts/generic/index.ts:49:19 - error TS2339: Property 'cards' does not exist on type 'void | ResponseData<IHomeData>'.
  Property 'cards' does not exist on type 'void'.
49   console.log(res.cards)
[12:49:06] Found 1 error. Watching for file changes.

检查发现then方法中的的res类型是void | ResponseData<IHomeData>,大致判断错误提示是因为联合类型包含了void,这又是为什么呢?

参考的是typescript教程中的介绍泛型的例子在这里深入理解 TypeScript#配合 axios 使用

源码如下

import Axios from 'axios'

export interface ResponseData<T = any> {
  code: number;
  msg: string;
  message: string;
  data: T;
}

export interface IHomeData {
  // ...
  cards: {
    [key: string]: any
  }[],
  // ....
}

export function getHomeData<T>() {
  return Axios.get<ResponseData<T>>('http://localhost:3000/home')
    .then(res => {
      if (!res.data) {
        throw new Error('请求错误')
      }
      return res.data
    })
    .catch(e => console.error(e))
}

getHomeData<IHomeData>().then(res => {
  // res的类型是void | ReponseData<IHomeData>获取不到cards属性???
  console.log(res.cards)
})

tsconfig.json

{
  "include": [
    "./**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    "target": "ES5",
    "outDir": ".",
    "moduleResolution": "node",
    "module": "commonjs",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "lib": [
      "DOM",
      "ES6",
      "ES2015",
      "ES2015.Promise"
    ]
  }
}
阅读 9.9k
1 个回答

三处错误:

export function getHomeData<T>() {
    return Axios
        .get<ResponseData<T>>('http://localhost:3000/home')
        .then(res => {
            if (!res.data) {
                throw new Error('请求错误')
            }
            
            return Promise.resolve(res.data.data); // res.data 是 axios 包装的 AxiosResponse<T> ,再 .data 才是你自己定义的 ResponseData<T>;另外尽可能用 Promise.resolve 包裹起来,以防 polyfill 时出现兼容问题。
        })
        .catch(e => {
            console.error(e);
            return Promise.reject(e); // 异常捕捉后被你吞了,相当于返回了 Promise<void>;所以需要继续向上抛出。
        })
}
推荐问题