定义我想要作为输入的函数类型:Typescript
我想确保我的输入只接受以下函数作为参数:定义我想要作为输入的函数类型:Typescript,typescript,types,typescript-typings,Typescript,Types,Typescript Typings,我想确保我的输入只接受以下函数作为参数: async getAll<T extends Entity>(url: string, params?: any): Promise<T[]> { // func body } 我想用自定义类型替换any 提前感谢。您可以为此使用界面或类型 类型: type TGetAllFunc<T extends Entity> = (url: string, params? : any) => Prom
async getAll<T extends Entity>(url: string, params?: any): Promise<T[]> {
// func body
}
我想用自定义类型替换any
提前感谢。您可以为此使用界面或类型 类型:
type TGetAllFunc<T extends Entity> = (url: string, params? : any) => Promise<T[]>;
interface IGetAllFunc<T extends Entity> {
(url: string, params? : any): Promise<T[]>;
}
typetgetallfunc=(url:string,params?:any)=>Promise;
界面:
type TGetAllFunc<T extends Entity> = (url: string, params? : any) => Promise<T[]>;
interface IGetAllFunc<T extends Entity> {
(url: string, params? : any): Promise<T[]>;
}
接口IGetAllFunc{
(url:string,params?:any):承诺;
}
然后您可以将其中一个传递给函数(我在这里的接口中传递):
setFunc(getAllFunc:IGetAllFunc){
this.func=getAllFunc;
}
根据您的函数,getAll
函数的类型如下:
type FunctionType<T> = (string, any) => Promise<T[]>;
似乎您将getAllFunc
设置为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;
}
/* ... */
}
type FunctionType=(字符串,任意)=>Promise;
类SomeClass{//命名为SomeClass为简洁起见,请在此处使用您自己的名称
func:FunctionType
setFunc(getAllFunc:FunctionType){
this.func=getAllFunc;
}
/* ... */
}
它说泛型类型'IGetAllFunc'需要1个类型参数
当我替换any
Oops对不起,忘记将T传递给IGetFunc
时,我更新了答案。现在能用了吗?
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;
}
/* ... */
}