在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"
]
}
}
三处错误: