【发布时间】:2021-09-12 01:24:12
【问题描述】:
我正在寻找一种方法来定义具有两个函数的对象,其中一个函数总是将另一个函数的返回类型作为参数。例如
type DoActionArgType = { contactId: string };
type Args<T> =
{
doAction: (arg: DoActionArgType) => string; // <-- returns string
onEnd?: (arg: string) => void; // <-- takes string as the argument
}
现在我希望它适用于任意返回类型和承诺,这很好,除非我不将类型添加到函数 doAction 函数参数中。
export type $Unwrap<T> = T extends Promise<infer U>
? U
: T extends (...args: any) => Promise<infer U>
? U
: T extends (...args: any) => infer U
? U
: T;
type DoActionArgType = { contactId: string };
type Args<T> =
{
doAction: (arg: DoActionArgType) => Promise<T>;
onEnd?: (arg: $Unwrap<T>) => void;
}
function test<T>(arg: Args<T>) {}
const doAction = async ({ contactId }) => 1
test({
// doAction: async ({ contactId }: DoActionArgType) => 1, // Works
// doAction: async () => 1, // Works
// doAction, // Works
doAction: async ({ contactId }) => 1, // <--- Does not work
onEnd: (arg) => {
const a:number = arg
}
})
我假设打字稿不理解函数签名匹配?因为contactId 实际上输入了string,只是onEnd 的arg 输入了unknown。有没有办法在不将DoActionArgType 类型添加到doAction 函数的情况下完成这项工作?
【问题讨论】:
-
你需要
$Unwrap类型做什么,为什么不直接使用onEnd?: (arg: T) => void -
@MrCodingB
(arg: T) => void不起作用
标签: typescript