目前我有类型定义为:

interface Param {
    title: string;
    callback: any;
}

我需要这样的东西:

interface Param {
    title: string;
    callback: function;
}

但是第二项不被接受。


当前回答

全局类型Function用于此目的。

此外,如果你打算用0个参数调用这个回调函数并忽略它的返回值,type () => void匹配所有不带参数的函数。

其他回答

从v1.4开始的Typescript有type关键字,它声明了一个类型别名(类似于C/ c++中的typedef)。你可以这样声明你的回调类型:

type CallbackFunction = () => void;

它声明了一个不接受参数且不返回任何值的函数。接受零个或多个任意类型参数且不返回任何值的函数是:

type CallbackFunctionVariadic = (...args: any[]) => void;

然后你可以说,例如,

let callback: CallbackFunctionVariadic = function(...args: any[]) {
  // do some stuff
};

如果你想要一个函数接受任意数量的参数并返回任何值(包括void):

type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;

你可以指定一些强制性参数,然后是一组额外的参数(比如一个字符串,一个数字,然后是一组额外的参数),这样:

type CallbackFunctionSomeVariadic =
  (arg1: string, arg2: number, ...args: any[]) => void;

这对于EventEmitter处理器之类的东西很有用。

在这种方式下,函数的类型可以随心所欲,尽管如果您试图用类型别名确定所有内容,可能会失去控制并遇到组合问题。

希望这对你有所帮助……

interface Param {
    title: string;
    callback: (error: Error, data: string) => void;
}

或在函数中


let myfunction = (title: string, callback: (error: Error, data: string) => void): string => {

    callback(new Error(`Error Message Here.`), "This is callback data.");
    return title;

}

根据Ryan的回答,我认为你所寻找的接口定义如下:

interface Param {
    title: string;
    callback: () => void;
}

如果您正在寻找类似于change事件的输入回调函数,则使用以下方法

type Props = {
  callBack:  ChangeEventHandler<HTMLInputElement>;
}

在typescript 4.8中,函数类型给出错误。相反,我们可以显式地将类型写为fn: () => void。

如果你也想使用args,

函数debounce(fn:(…参数:any[]) => void, ms = 300) {