Issue
I get an error:
Property 'ip' does not exist on type 'IpDetails | Error'.
Property 'ip' does not exist on type 'Error'.ts(2339)
Even if I checked the type by ("message" in res)
or used isError
to narrow the type. Am I doing something wrong or is it TypeScript's bug?
interface IpDetails {
ip : string,
}
interface Error {
error: {
code : number,
message: string,
},
}
let collection: IpDetails[] = [];
function isError(res: any | Error): res is Error {
return (res as Error).error !== undefined;
}
const getIpData = async (ipAddress: string, config: any = {}): Promise<IpDetails|Error> => {
return new Promise((resolve, reject) => {
resolve({ip : '1.1.1.1'});
});
}
(async () => {
let res = await getIpData('1.1.1.1');
if (!isError(res)) { // if ('error' in res)
let dublicate = collection.find(entry => entry.ip === res.ip); // <--- ERROR
}
})();
Solution
collection.find(entry => entry.ip === res.ip);
When you have code in a callback function, typescript does not know when that function is going to be called. You and i know that the .find
callback is called synchronously, but the type information can not indicate that. So typescript has to assume the worst case: that this code could be called at some arbitrary point in the future (like what happens with setTimeout). This means the check you just did for isError
may no longer be accurate, because some piece of code may have reassigned res
in the meantime.
The simplest way to fix this is to make res
a const. That way, typescript can be sure that if the check was accurate at one point, it will always be accurate.
(async () => {
const res = await getIpData('1.1.1.1');
if (!isError(res)) {
let dublicate = collection.find(entry => entry.ip === res.ip);
}
})();
Answered By - Nicholas Tower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.