带有承诺的打字稿索引签名
以下课程的正确索引签名是什么?
class MyClass {
[index: string]: Promise<void> | Promise<MyType>; // not working
public async methodOne (): Promise<void> { ... }
public async methodTwo (): Promise<MyType> { ... }
}
我希望能够使用该方法的字符串名称在此类上执行方法:
myClassInstance[stringNameOfMethodOne]()
有两个打字稿错误,一个在方法定义上,一个在方法的使用中。方法定义错误是:
Property 'methodOne' of type '() => Promise<void>' is not assignable to 'string' index type 'Promise<void> | Promise<MyType>'
使用该方法的错误是:
This expression is not callable. No constituent of type 'Promise<MyType> | Promise<void>' is callable.
我已经在JavaScript中完成了此操作,但是对Typescript的索引签名不太熟悉。
What is the correct index signature for the following class?
class MyClass {
[index: string]: Promise<void> | Promise<MyType>; // not working
public async methodOne (): Promise<void> { ... }
public async methodTwo (): Promise<MyType> { ... }
}
I want to be able to execute a method on this class using the string name of the method:
myClassInstance[stringNameOfMethodOne]()
There are two TypeScript errors, one on the method definition and one on the usage of the method. The method definition error is:
Property 'methodOne' of type '() => Promise<void>' is not assignable to 'string' index type 'Promise<void> | Promise<MyType>'
The error on the usage of the method is:
This expression is not callable. No constituent of type 'Promise<MyType> | Promise<void>' is callable.
I've done this in JavaScript but am less familiar with TypeScript's index signatures.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能只是忘记了功能类型:
You probably just forgot the function type:
您可能根本不想要索引签名。因为此功能正常:
String nameofmethodone
实际上是字符串字面类型,因此TypeScript确切知道它将查找什么属性,这使所有内容都可以正常工作。You may not want an index signature at all. Because this works fine:
stringNameOfMethodOne
here is actually a string literal type, so typescript knows exactly what property it will look up, which makes everything work.