如何通过回调函数声明类型';Typescript中的参数类型是什么?
如何声明回调函数句柄的参数类型如何通过回调函数声明类型';Typescript中的参数类型是什么?,typescript,Typescript,如何声明回调函数句柄的参数类型 const util = (handle: (p) => string) => ({ // I expect log function's param [p]'s type come from handle function's param's type log: (p: Parameters<typeof handle>[0]) => console.log(handle(p)) }); // But now the lo
const util = (handle: (p) => string) => ({
// I expect log function's param [p]'s type come from handle function's param's type
log: (p: Parameters<typeof handle>[0]) => console.log(handle(p))
});
// But now the log function param is recognized as any type not string
const { log } = util((a: string) => String(a));
constutil=(句柄:(p)=>string)=>({
//我希望log函数的param[p]类型来自handle函数的param类型
log:(p:Parameters[0])=>console.log(handle(p))
});
//但是现在log函数param被识别为任何类型,而不是字符串
const{log}=util((a:string)=>string(a));
//Expectlog函数参数为字符串const{log}=util((a:string)=>string(a))代码>
//Expectlog函数参数为int
const{log}=util((a:int)=>String(a))代码>
//Expectlog函数参数为对象
const{log}=util((a:object)=>String(a))代码>
我知道该类型可以用泛型的方式指定,但我想知道该类型是否已在回调函数的参数签名中声明,是否可以转发该类型?尝试以下操作:
constutil=(句柄:(arg:T)=>string)=>({
//我希望log函数的param[p]类型来自handle函数的param类型
log:(p:T)=>console.log(handle(p))
});
您只需声明泛型参数,TS将推断它您可以使用泛型类型获得它
const util = <T>(handle: (p: T) => string) => ({
// I expect log function's param [p]'s type come from handle function's param's type
log: (p: T) => console.log(handle(p))
});
// Expect log function param is string
const { log } = util<Number>((a) => String(a));
log(1); // Param type number
const { log: log1 } = util<String>((a) => String(a));
log1('1'); // Param type string
const { log: log2 } = util<Object>((a) => String(a));
log2({}); // Param type object
const { log: log3 } = util((a) => String(a));
log3(''); // Param type any
constutil=(句柄:(p:T)=>string)=>({
//我希望log函数的param[p]类型来自handle函数的param类型
log:(p:T)=>console.log(handle(p))
});
//预期日志函数param为string
const{log}=util((a)=>String(a));
日志(1);//参数类型号
const{log:log1}=util((a)=>String(a));
log1('1');//参数类型字符串
const{log:log2}=util((a)=>String(a));
log2({});//参数类型对象
const{log:log3}=util((a)=>String(a));
log3(“”);//参数类型任意
谢谢您的回答,我现在就是这么做的,但我想知道它是否可以通过传递回调函数自动实现。您不应该使用T=any
。TS将推断type@captain-yossarian感谢您的建议。@PankajPrakash您也可以在此处删除显式泛型参数util
。顺便说一句,使用string
或number
类型,而不是number
和string
。大写类型是类的类型,而不是原语的类型谢谢你的回答,这是我现在做的,但我想知道它是否可以通过传递回调函数自动实现。该类型已在回调函数的参数签名中声明,该类型可以转发吗?但它已经是自动的。不需要定义任何显式泛型constresult=util((arg:number)=>hello')/{log:(p:number)=>void;}