我想在Typescript中定义一个名为Callbackify的泛型函数类型,该函数具有以下功能:
我想将其用作该callbackify函数的返回类型:
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(children: [
TextFormField(validator: (value) {
if (value.isEmpty) {
return "Please Fill";
}
}),
TextFormField(validator: (value) {
if (value.isEmpty) {
return "Please Fill";
}
}),
RaisedButton(
child: Text("Submit"),
onPressed: () async {
if (_formKey.currentState.validate()) {
return;
}
_formKey.currentState.save();
//Some Codes
},
)
]),
),
该函数的一些用例是:
function callbackify<E>(executor: () => Promise<E>): Callbackify<E> {
// omitted implementation
}
我尝试了以下方法,但是它似乎无法按预期工作(它总是返回void)
const fn = callbackify(() => Promise.resolve(4));
// given a callback function as an argument, so should return void
let returnValue = fn((err, value) => { console.log(err, value) })
typeof returnValue // void
//given no argument, so should return Promise<number>
let returnValue = fn()
typeof returnValue // Promise<number>
答案 0 :(得分:1)
我只会使用重载。重载是您尝试做的更好的选择:
export type CallbackFunction<T> = (error: Error | null, value?: T) => void;
export type Callbackify<E> = {
(done: CallbackFunction<E>): void;
(): Promise<E>;
}
function callbackify<E>(executor: () => Promise<E>): Callbackify<E> { // Explicit return type not really necesarry
function callbackified(done: CallbackFunction<E>): void;
function callbackified(): Promise<E>;
function callbackified(done?: CallbackFunction<E>): Promise<E> | void {
return null!
}
return callbackified;
}