推断TypeScript中函数的类型对象
我尝试使用泛型推断函数参数(对象)的类型,并在该参数内的函数中使用它 我想推断函数中推断TypeScript中函数的类型对象,typescript,flowtype,Typescript,Flowtype,我尝试使用泛型推断函数参数(对象)的类型,并在该参数内的函数中使用它 我想推断函数中po的类型: run({ methods: { calculateNumber: po => (num: number) => po.methods.isActive() ? num : 0, isActive: po => () => true, }, }); // I want infer follow type corresponding `po` // t
po
的类型:
run({
methods: {
calculateNumber: po => (num: number) => po.methods.isActive() ? num : 0,
isActive: po => () => true,
},
});
// I want infer follow type corresponding `po`
// type PO = {
// methods: {
// calculateNumber: (num: number) => number,
// isActive: () => boolean,
// }
// }
我所做的:
// type of po in nested functions
type PO<M> = {
methods: {
[K in keyof M]: M[K] extends (...args: any[]) => (...args: infer R) => any ? (...args: R) => any : 'GetMethod never';
};
};
// incoming type
type Options<M> = {
methods: {
[K in keyof M]: M[K] extends (...args: any[]) => (...args: infer R) => any ? (PO: PO<M>) => (...args: R) => any : 'Options never';
// L___ I suppose here type should infer
};
};
function run<M>(options: Options<M>) {
return {} as any;
}
po
推断为键入po
,但我希望po
如果我向方法添加了任何基元类型,则使用正确的键键入M
infere,但使用错误的类型(如“Options never”):
如果我使用不带函数的基元类型,则此代码的工作方式与预期相同
我的问题:为什么TS不能推断函数的类型(但可以与基元类型一起工作),或者我做错了什么
打字稿:
流程中的工作代码相同:
/* @flow */
type GetMethod = <R>((...any) => R) => R;
type PO<M> = {|
methods: {
...$Exact<$ObjMap<M, GetMethod>>,
};
|};
type Methods<P, K> = {|
[K]: P => (...any) => any,
|}
type Options<M> = {|
methods: M & Methods<PO<M>, $Keys<M>>;
|};
function run<M>(options: Options<M>) {
return ({}: any);
}
run({
methods: {
calculateNumber: po => (num: number) => po.methods.isActive() ? num : 0,
isActive: po => () => true,
},
});
/*@flow*/
键入GetMethod=(…任意)=>R)=>R;
采购订单类型={|
方法:{
…准确地说,
};
|};
类型方法={|
[K] :P=>(…任意)=>任意,
|}
类型选项={|
方法:M&M方法;
|};
函数运行(选项:选项){
返回({}:任何);
}
跑({
方法:{
CalculateEnumber:po=>(num:number)=>po.methods.isActive()?num:0,
isActive:po=>()=>正确,
},
});
run({
methods: {
foo: 'bar',
calculateNumber: po => (num: number) => po.methods.isActive() ? num : 0,
// ^^^^^^^^^^^^^^^
// Type '(po: any) => (num: number) => number' is not assignable to type '"Options never"'
isActive: po => () => true,
// ^^^^^^^^
// Type '(po: any) => () => boolean' is not assignable to type '"Options never"'
},
});
/* @flow */
type GetMethod = <R>((...any) => R) => R;
type PO<M> = {|
methods: {
...$Exact<$ObjMap<M, GetMethod>>,
};
|};
type Methods<P, K> = {|
[K]: P => (...any) => any,
|}
type Options<M> = {|
methods: M & Methods<PO<M>, $Keys<M>>;
|};
function run<M>(options: Options<M>) {
return ({}: any);
}
run({
methods: {
calculateNumber: po => (num: number) => po.methods.isActive() ? num : 0,
isActive: po => () => true,
},
});