I have an arrow function, which compares two values. One value comes from another function, which gets the value from an API Endpoint. I would like to use the await / async style instead of Promises (.then, .catch, .finaly).
In JavaScript it's easy peasy, but I have some Problems with TypeScript. How to correctly write that function?
I have something like this (Pseudocode):
compareValues: Promise<boolean> = async () => { try { const value1 = false; const value2 = this.getValue2; const isEqual = (await value2) === value1; return isEqual; } catch (error) { throw error; } } getValue2 = async () => { try { const value2 = await axios.get(url, config); const value2Data = await value2.data; return value2Data; } catch (error) { throw error; } export interface IInterface { compareValues: () => Promise<boolean>; } const initialState: IInterface = { compareValues: () => { return Promise.resolve(false); } } With that code the IDE cries for the first line: Type '() => Promise' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag]
While the compiler tells: Type 'Promise' is not assignable to type '() => Promise'. Type 'Promise' provides no match for the signature '(): Promise'. TS2322
I have the feeling my return type is wrong...
Will the code wrap my isEqual value in a Promise?
Can I avoid that both functions are async?
What would be the right Syntax?
Thank you in advance!
compareValues: Promise<boolean>should becompareValues: () => Promise<boolean>- after allcompareValuesholds a function that will produce a promise when called. It's not an actual promise right now. If you instead need the promise itself, then you need to call the function.compareValues: Promise<boolean> = async () => {tocompareValues = async () => {and it's working.