'TypeScript error - property 'xyz' does not exist on type { }
I have a simple JavaScript function (in a .tsx file)
export async function addDealer(payload: object) {
let tempSupplierId = "cc9cfc30-5c01-11ec-bf63-0242ac130002"
let addDealerURL = URLMap("addDealerAPI")
addDealerURL = addDealerURL.replace("{supplierId}", tempSupplierId)
let result = {}
try {
result.data = await fetch(addDealerURL, { //line 39
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
} catch (e) {
result.error = e //line 47
}
return result;
}
It gives compile errors like
property 'data' does not exist on type '{}' and
property 'error' does not exist on type '{}' due to lines 39 and 47. This is a valid code in plain JavaScript, but TypeScript won't allow because result - {}.
I understand these are valid errors and why they are appearing. I just don't know how to solve these.
I tried defining a type at the top of the file as below:
type resultType = {
data: any;
error: any;
}
And in the function, defined a result as resultType.
let result: resultType
With this change I get new errors as:
Variable 'result' is used before being assigned.
I am confused with TypeScript, as I am still getting acquanted with it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
