[英]Defining type of function which I want to take as an input : Typescript
I want to make sure that my input accepts only below function as an argument:我想确保我的输入仅接受低于 function 作为参数:
async getAll<T extends Entity>(url: string, params?: any): Promise<T[]> {
// func body
}
My function :我的 function :
setFunc(getAllFunc: any){
this.func = getAllFunc;
}
I want to replace any
with custom type.我想用自定义类型替换
any
。
Thanks in advance.提前致谢。
You can either use an interface or a type for this.您可以为此使用接口或类型。
Type:类型:
type TGetAllFunc<T extends Entity> = (url: string, params? : any) => Promise<T[]>;
Interface:界面:
interface IGetAllFunc<T extends Entity> {
(url: string, params? : any): Promise<T[]>;
}
Then you can pass in either one to the function(I passed in the Interface here):然后你可以将其中一个传递给函数(我在这里传递了接口):
setFunc(getAllFunc: IGetAllFunc<Entity>){
this.func = getAllFunc;
}
Based on your function the type of your getAll
function is as follows:根据您的 function 您的
getAll
function 的类型如下:
type FunctionType<T> = (string, any) => Promise<T[]>;
You can then rewrite your function setFunc
to take in the function type.然后,您可以重写您的 function
setFunc
以采用 function 类型。
setFunc(getAllFunc: FunctionType<T>){
this.func = getAllFunc;
}
It seems like you set getAllFunc
to class property, so that means that you would need to have your class also generic.似乎您将
getAllFunc
设置为 class 属性,这意味着您需要让您的 class 也是通用的。 so your class would look something like this,所以你的 class 看起来像这样,
type FunctionType<T> = (string, any) => Promise<T[]>;
class SomeClass<T> { // named SomeClass for brevity, use your own name here
func: FunctionType<T>
setFunc(getAllFunc: FunctionType<T>){
this.func = getAllFunc;
}
/* ... */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.