为了说明这个例子,假设我想编写一个函数,将日志记录添加到任何返回 Promise 的函数中。在JS中,我会做这样的事情:
const addLogging = (f) => (...args) => (
f(...args).then(result => {
console.log('result:', result);
return result;
})
)
const test = addLogging(
(value) => Promise.resolve(value)
)
test('foo') // logs "result: foo"
现在我想用打字稿强制执行打字。这是我想到的:
const addLogging = <F extends Function>(f: F): F => (
(
(...args: any[]) => (
(f as any)(...args).then((result: any) => {
console.log('result:', result);
return result;
})
)
) as any
);
// Cool! :)
// type of test is (value: string) => Promise<string>
const test = addLogging(
(value: string) => Promise.resolve(value),
);
// Less Cool :(
// Not valid, how to prevent it with typings?
const test2 = addLogging(
(value: string) => value, // should return a promise
);
保留了增强功能的键入,这很好。但首先我必须使用很多any
,而且我还想强制addLogging
的f
参数必须是返回Promise
的函数。有没有简单的方法可以用打字稿做到这一点?
您可以更具体地说明对F
的约束,您可以指定 这是一个接受任意数量的参数并返回Promise<any>
const addLogging = <F extends (...args: any[]) => Promise<any>>(f: F) => ((
(...args) =>
f(...args).then((result: any) => {
console.log('result:', result);
return result;
})
) as F);
//Ok
const test = addLogging(
(value: string) => Promise.resolve(value),
);
//Error
const test2 = addLogging(
(value: string) => value, // should return a promise
);