我使用fetch
从API查询一些JSON数据。
我编写的助手函数返回一个Promise<Response>
(这是一个简化版本(
const apiCall = (): Promise<Response> => fetch('http://the.api.com').then(r => r.json())
然后我这样使用它:
export class Case {
Uuid?: string
Topic?: string
public constructor(init?:Partial<Case>) {
Object.assign(this, init);
}
}
callApi()
.then(r => allCases.value = r.Data as Array<Case>) // the error is on this line
.catch(() => {{}})
我的问题:TypeScript报告错误:
TS2339: Property 'Data' does not exist on type 'Response'.
无论如何,该程序都能成功通过,但我想了解并修复这个错误(主要是为了更好地理解TS(。
然后我尝试用预期的类型提示r
:
interface ApiResponse {
Data: Array<Case>
}
callApi('/case', 'GET')
.then((r: ApiResponse) => allCases.value = r.Data as Array<Case>)
.catch(() => {{}})
这现在带来了两个错误:
TS2345: Argument of type '(r: ApiResponse) => Case[]' is not assignable to parameter of type '(value: Response) => Case[] | PromiseLike<Case[]>'.
Types of parameters 'r' and 'value' are incompatible.
Property 'Data' is missing in type 'Response' but required in type 'ApiResponse'.
ESLint: This assertion is unnecessary since it does not change the type of the expression. (@typescript-eslint/no-unnecessary-type-assertion)
如何表达来自助手函数的内容应被视为对象(使用Data
键(
您可以如下定义callApi
:
const callApi = (): Promise<ApiResponse> => fetch('http://the.api.com').then(r => r.json())
查看node-fatch的类型定义告诉我:
fetch
的返回类型为Promise<Response>
Response.json
的返回类型为Promise<unknown>
所以callApi
函数的返回类型是Promise<unknown>
,而不是Promise<Response>
。
那么这应该起作用:
callApi().then(r => allCases.value = r.Data).catch(() => {{}})
为什么您的解决方案不起作用:
callApi('/case', 'GET')
.then((r: ApiResponse) => allCases.value = r.Data as Array<Case>)
.catch(() => {{}})
在这里,您将一个类型错误的回调函数作为参数传递给then
,因为r
的类型不是ApiResponse
,而是您以前键入的Response
。这会导致TS错误。