[英]In typescript, how to define type of async function
我试图定义一种异步函数,但编译失败,见下文:
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 ''
}
}
谁能帮我解决这个问题?
发现这个搜索如何为异步箭头函数声明“typedef”。
如果你只是将函数的返回类型声明为一个 Promise,它就可以工作:
interface SearchFn {
(subString: string): Promise<boolean>;
}
或作为类型声明:
type SearchFn = (subString: string) => Promise<boolean>;
Microsoft 的 TS Linter 将推荐第二种语法。
async
关键字用于向编译器/运行时指示相关函数将await
内部使用await
(因此它可以放入所需的脚手架以启用它)。
这意味着async
只对函数的实现有意义,而不是interface 。 因此,在接口的方法上使用async
没有用,您想说该函数返回某个Promise
(在您的情况下为Promise<string>
),但您不想强制接口的实现者以某种方式实现它(使用await
)。
所以正如其他人在我之前所说:
interface SearchFn {
(subString: string): Promise<string>;
}
然后,任何选择实现此功能的人都可以选择使用async
、普通的旧Promise.then
或者甚至一些将来会出现的新方法。
将返回对象的类型传递给 Promise 泛型。
type SearchFn = (subString: string): Promise<string>;
或者,您可以声明AsyncFunction
泛型类型。
type AsyncFunction <A,O> = (...args:A) => Promise<O>
type SearchFn = AsyncFunction<[string], string>
AsyncFunction 是一个类型泛型,它接收两个类型变量——输入(A)的类型和输出的类型。
简单的方法。
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
要么
const SignUp = async (userInfo: SignUpType): Promise<SignUpReturn> => {
try {
const data = await client.request(query, userInfo)
return data
} catch (error) {
throw error
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.