目前我有类型定义为:
interface Param {
title: string;
callback: any;
}
我需要这样的东西:
interface Param {
title: string;
callback: function;
}
但是第二项不被接受。
目前我有类型定义为:
interface Param {
title: string;
callback: any;
}
我需要这样的东西:
interface Param {
title: string;
callback: function;
}
但是第二项不被接受。
当前回答
我刚开始使用Typescript,我一直试图解决类似的问题,就像这样;如何告诉Typescript我正在传递一个没有接口的回调。
在浏览了Stack Overflow和GitHub问题的一些答案后,我终于找到了一个解决方案,可以帮助任何有同样问题的人。
函数的类型可以用(arg0: type0) => returnType定义,并且可以在另一个函数的形参列表中使用此类型定义。
function runCallback(callback: (sum: number) => void, a: number, b: number): void {
callback(a + b);
}
// Another way of writing the function would be:
// let logSum: (sum: number) => void = function(sum: number): void {
// console.log(sum);
// };
function logSum(sum: number): void {
console.log(`The sum is ${sum}.`);
}
runCallback(logSum, 2, 2);
其他回答
如果您正在寻找类似于change事件的输入回调函数,则使用以下方法
type Props = {
callBack: ChangeEventHandler<HTMLInputElement>;
}
有四种抽象函数类型,当你知道你的函数是否接受参数,是否返回数据时,你可以分别使用它们。
export declare type fEmptyVoid = () => void;
export declare type fEmptyReturn = () => any;
export declare type fArgVoid = (...args: any[]) => void;
export declare type fArgReturn = (...args: any[]) => any;
是这样的:
public isValid: fEmptyReturn = (): boolean => true;
public setStatus: fArgVoid = (status: boolean): void => this.status = status;
为了只使用一种类型作为任何函数类型,我们可以将所有抽象类型组合在一起,如下所示:
export declare type fFunction = fEmptyVoid | fEmptyReturn | fArgVoid | fArgReturn;
然后这样使用它:
public isValid: fFunction = (): boolean => true;
public setStatus: fFunction = (status: boolean): void => this.status = status;
在上面的例子中,一切都是正确的。但是从大多数代码编辑器的角度来看,下面的使用示例是不正确的。
// you can call this function with any type of function as argument
public callArgument(callback: fFunction) {
// but you will get editor error if call callback argument like this
callback();
}
正确的编辑召唤是这样的:
public callArgument(callback: fFunction) {
// pay attention in this part, for fix editor(s) error
(callback as fFunction)();
}
全局类型Function用于此目的。
此外,如果你打算用0个参数调用这个回调函数并忽略它的返回值,type () => void匹配所有不带参数的函数。
根据Ryan的回答,我认为你所寻找的接口定义如下:
interface Param {
title: string;
callback: () => void;
}
你可以用多种方式在接口中定义函数类型,
一般方法:
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
如果你想使用属性语法,
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
如果先声明函数类型,
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
使用非常直接,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
你也可以声明一个函数类型文字,这意味着一个函数可以接受另一个函数作为它的形参。参数化函数也可以作为回调函数调用。
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}