Using the fetch
method, I make a request to an API to retrieve JSON data.
The custom function that I created returns a Promise<Response>
(this is a simplified version).
const getData = (): Promise<Response> => fetch('http://the.api.com').then(response => response.json())
This is how I implement it:
export class Case {
Uuid?: string
Topic?: string
public constructor(init?:Partial<Case>) {
Object.assign(this, init);
}
}
getData()
.then(response => allCases.value = response.Data as Array<Case>) // the error occurs in this line
.catch(() => {{}})
The issue I'm facing: TypeScript shows me an error message:
TS2339: Property 'Data' does not exist on type 'Response'.
The application still runs successfully, but I would like to resolve this error for better understanding of TypeScript in general.
I attempted to specify the type for response
:
interface ApiResponse {
Data: Array<Case>
}
getData('/case', 'GET')
.then((response: ApiResponse) => allCases.value = response.Data as Array<Case>)
.catch(() => {{}})
Now, two errors are displayed:
TS2345: Argument of type '(response: ApiResponse) => Case[]' is not assignable to parameter of type '(value: Response) => Case[] | PromiseLike<Case[]>'.
Types of parameters 'response' 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)
How can I indicate that the output from my custom function should be treated as an Object with a Data
key?