In typescript, how to determine the type of an asynchronous function

I tried to determine the type of the async function, but failed to compile, see below:

interface SearchFn {
    async (subString: string): string;
}

class A {
    private Fn: SearchFn
    public async do():Promise<string> {
        await this.Fn("fds") // complain here: cannot invoke an expression whose type lacks a call signature
        return ''
    }
}

Can someone help me deal with this?

+39
source share
4 answers

Found this search how to declare a "typedef" for an asynchronous arrow function.

This works if you simply declare the return type of the Promise function:

interface SearchFn {
    (subString: string): Promise<boolean>;
}

or as type declaration:

type SearchFn = (subString: string) => Promise<boolean>;
+84
source

Pass the return type to the generic Promise object.

type SearchFn = (subString: string): Promise<string>;
}

Alternatively, you can declare a generic type AsyncFunction.

type AsyncFunction <A,O> = (...args:A) => Promise<O> 
type SearchFn = AsyncFunction<[string], string>

AsyncFunction is a generic type that receives two type variables - input type (A) and output type.

+2

async , / , await ( ).

, async , . async , , Promise ( Promise<string>), , . ( await).

:

interface SearchFn {
    (subString: string): Promise<string>;
}

Then the one who decides to implement this function can use a asyncsimple old Promise.thenor, perhaps, even some new methodology that will appear in the future.

+2
source

The simple way.

export interface SignUpReturn {
  user_id: string
  platform: string
  name: string
  image_url: string
  email: string
}

export interface SignUpType {
  platform: string
  loginId: string
  password: string
  name: string
  email: string
}

const SignUp = async (userInfo: SignUpType) => {
  try {
    const data: SignUpReturn = await client.request(query, userInfo)
    return data
  } catch (error) {
    throw error
  }
}

export default SignUp

or

const SignUp = async (userInfo: SignUpType): Promise<SignUpReturn> => {
  try {
    const data = await client.request(query, userInfo)
    return data
  } catch (error) {
    throw error
  }
}
+1
source

Source: https://habr.com/ru/post/1650035/


All Articles